ElasticSearch[02]ElasticSearchJavaAPI

ElasticSearch[02]ElasticSearchJavaAPI,第1张

ElasticSearch[02]ElasticSearchJavaAPI

参考视频

【狂神说Java】ElasticSearch7.6.x最新完整教程通俗易懂 P13.

【狂神说Java】ElasticSearch7.6.x最新完整教程通俗易懂 P14.

环境准备 软件版本ElasticSearch7.8.1IDEA2021.2ElasticSearch Head0.1.5

创建普通maven项目

pom.xml

添加依赖

    
        
            org.projectlombok
            lombok
            1.18.22
        
        
            com.alibaba
            fastjson
            1.2.75
        
        
            junit
            junit
            4.13.1
            compile
        
        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            7.8.1
        
        
        
            org.apache.logging.log4j
            log4j-core
            2.13.3
        
        
            org.apache.logging.log4j
            log4j-api
            2.13.3
        
    
log4j2.xml

resources配置log4j2.xml



    
        
            
        
    

    
        
            
        
    

ElasticSearchClientConfig.java

编写ElasticSearchClient配置类

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

public class ElasticSearchClientConfig {
    public static RestHighLevelClient getRestHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
        );
        return client;
    }
}
user.java

编写pojo实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;
    private int age;
}
APITest.java

创建测试类编写测试方法

import com.alibaba.fastjson.JSON;
import com.elasticsearch.api.config.ElasticSearchClientConfig;
import com.elasticsearch.api.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.Timevalue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class APITest {
    RestHighLevelClient client;
    
    @Before
    public void before() {
        client=ElasticSearchClientConfig.getRestHighLevelClient();
    }
}
ElasticSearch Java API测试 创建索引
    //创建索引
    @Test
    public void testCreateIndex() throws IOException {
        //创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("user_index");
        //执行创建请求
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        //打印运行结果
        System.out.println(createIndexResponse.isAcknowledged());
    }
true
获取索引
    //获取索引
    @Test
    public void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("user_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
true
删除索引
    //删除索引
    @Test
    public void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("user_index");
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }
true
添加数据到测试文档
    //添加数据到测试文档
    @Test
    public void testAdddocument() throws IOException {
        //创建对象
        User user = new User("aa", 12);

        //创建请求
        IndexRequest request = new IndexRequest("user_index");

        //规则 put /user_index/_doc/1
        request.id("1");//若不设置id则生成随机id
        //响应时间
        //request.timeout(Timevalue.timevalueSeconds(1));
        request.timeout("1s");

        //将数据放入请求
        request.source(JSON.toJSONString(user), XContentType.JSON);

        //客户端发送请求,获取响应结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse.toString());
        System.out.println(indexResponse.status());//对应命令返回状态
    }
IndexResponse[index=user_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
CREATED
文档主键查询
    //文档主键查询
    //获取测试文档,判断是否存在 get /index/doc/1
    @Test
    public void testExists() throws Exception {
        GetRequest user_index = new GetRequest("user_index", "1");
        //不获取返回的_source 的上下文
        user_index.fetchSourceContext(new FetchSourceContext(false));
        user_index.storedFields("_none_");

        boolean exists = client.exists(user_index, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
true
获得文档信息
    //获得文档信息
    @Test
    public void testGetdocuments() throws Exception {
        GetRequest user_index = new GetRequest("user_index", "1");
        GetResponse getResponse = client.get(user_index, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString());//打印文档的内容
        System.out.println(getResponse);
    }
{"age":12,"name":"aa"}
{"_index":"user_index","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"age":12,"name":"aa"}}
更新文档信息
    //更新文档信息
    @Test
    public void testUpdatedocuments() throws Exception {
        UpdateRequest updateRequest = new UpdateRequest("user_index", "1");
        updateRequest.timeout("1s");

        User bb = new User("bb", 18);
        updateRequest.doc(JSON.toJSONString(bb), XContentType.JSON);

        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse);
        System.out.println(updateResponse.status());
    }
UpdateResponse[index=user_index,type=_doc,id=1,version=2,seqNo=1,primaryTerm=1,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]
OK
删除文档记录
    //删除文档记录
    @Test
    public void testDeletedocuments() throws Exception {
        DeleteRequest deleteRequest = new DeleteRequest("user_index", "1");
        deleteRequest.timeout("1s");

        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse);
        System.out.println(deleteResponse.status());
    }
DeleteResponse[index=user_index,type=_doc,id=1,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
OK
批量添加数据到测试文档
    //批量添加数据到测试文档
    @Test
    public void testBulkRequest() throws Exception {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("1s");

        ArrayList userList = new ArrayList<>();
        userList.add(new User("aa", 11));
        userList.add(new User("bb", 12));
        userList.add(new User("cc", 13));
        userList.add(new User("dd", 14));
        userList.add(new User("ee", 15));

        int i = 1;
        for (User user : userList) {
            //批量更新和批量删除 处理请求
            bulkRequest.add(
                    new IndexRequest("user_index")
                            .id(i + "")
                            .source(JSON.toJSONString(user), XContentType.JSON)
            );
            i++;
        }

        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());//是否失败 false代表成功
    }
false
文档条件查询(高亮、分页)

多添加几条name=aa的数据用于测试

    //文档条件查询
    @Test
    public void testSearch() throws Exception {
            //文档条件查询
    @Test
    public void testSearch() throws Exception {
        SearchRequest searchRequest = new SearchRequest("user_index");
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        
//        MatchAllQueryBuilder termQueryBuilder = QueryBuilders.matchAllQuery();//matchAll匹配所有
        //查询条件可以使用QueryBuilders工具类实现
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "aa");//term精确匹配
        sourceBuilder.query(termQueryBuilder);
        
        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder
                .field("name")//高亮字段
                .requireFieldMatch(false)//是否每个字都高亮
                .preTags("")//高亮前缀
                .postTags("");//高亮后缀
        sourceBuilder.highlighter(highlightBuilder);
        
        sourceBuilder.from();//页码
        sourceBuilder.size();//每页条数
        sourceBuilder.timeout(new Timevalue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        
        System.out.println("*******打印文档内容*********");
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            System.out.println(documentFields.getSourceAsMap());
        }

        System.out.println("********内容高亮显示********");
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            Map highlightFields = documentFields.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            Map sourceAsMap = documentFields.getSourceAsMap();
            if (name != null) {
                Text[] fragments = name.fragments();
                String newTitle = "";
                for (Text text : fragments) {
                    newTitle += text;
                }
                sourceAsMap.put("name", newTitle);
            }
            System.out.println(sourceAsMap);
        }
    }
{"fragment":true,"hits":[{"fields":{},"fragment":false,"highlightFields":{"name":{"fragment":true,"fragments":[{"fragment":true}],"name":"name"}},"id":"1","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":0.7985077,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"aa","age":11},"sourceAsString":"{"age":11,"name":"aa"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{"name":{"fragment":true,"fragments":[{"fragment":true}],"name":"name"}},"id":"GI1_mH0BKTXNK4J9Fszy","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":0.7985077,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"aa","age":13},"sourceAsString":"{"age":13,"name":"aa"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{"name":{"fragment":true,"fragments":[{"fragment":true}],"name":"name"}},"id":"GY1_mH0BKTXNK4J9Qsxb","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":0.7985077,"seqNo":-2,"sortValues":[],"sourceAsMap":{"name":"aa","age":15},"sourceAsString":"{"age":15,"name":"aa"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}],"maxScore":0.7985077,"totalHits":{"relation":"EQUAL_TO","value":3}}
*******打印文档内容*********
{name=aa, age=11}
{name=aa, age=13}
{name=aa, age=15}
********内容高亮显示********
{name=aa, age=11}
{name=aa, age=13}
{name=aa, age=15}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5652321.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存