0


ElasticSearch中基础API操作

1:首先我们需要连接ElasticSearch客户端,需要一个连接操作: RestHighLevelClient

packagecom.atguigu.es.test;importorg.apache.http.HttpHost;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;publicclassESTest_Client{publicstaticvoidmain(String[] args)throwsException{// 创建ES客户端RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 关闭ES客户端
        esClient.close();}}

2:建立的客户端后,我们需要先进行索引的创建,查询,删除操作:

2.1:创建索引:

CreateIndexRequest

响应:

esClient.indices().create
packagecom.atguigu.es.test;importorg.apache.http.HttpHost;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.client.indices.CreateIndexRequest;importorg.elasticsearch.client.indices.CreateIndexResponse;publicclassESTest_Index_Create{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 创建索引CreateIndexRequest request =newCreateIndexRequest("user");CreateIndexResponse createIndexResponse =
                esClient.indices().create(request,RequestOptions.DEFAULT);// 响应状态boolean acknowledged = createIndexResponse.isAcknowledged();System.out.println("索引操作 :"+ acknowledged);

        esClient.close();}}

请添加图片描述

2.2:查询索引:

GetIndexRequest

响应:

esClient.indices().get
packagecom.atguigu.es.test;importorg.apache.http.HttpHost;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.client.indices.CreateIndexRequest;importorg.elasticsearch.client.indices.CreateIndexResponse;importorg.elasticsearch.client.indices.GetIndexRequest;importorg.elasticsearch.client.indices.GetIndexResponse;publicclassESTest_Index_Search{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 查询索引GetIndexRequest request =newGetIndexRequest("user");GetIndexResponse getIndexResponse =
                esClient.indices().get(request,RequestOptions.DEFAULT);// 响应状态System.out.println(getIndexResponse.getAliases());System.out.println(getIndexResponse.getMappings());System.out.println(getIndexResponse.getSettings());

        esClient.close();}}

2.3:删除索引:

DeleteIndexRequest

响应:

esClient.indices().delete
packagecom.atguigu.es.test;importorg.apache.http.HttpHost;importorg.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;importorg.elasticsearch.action.support.master.AcknowledgedResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.client.indices.GetIndexRequest;importorg.elasticsearch.client.indices.GetIndexResponse;publicclassESTest_Index_Delete{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 查询索引DeleteIndexRequest request =newDeleteIndexRequest("user");AcknowledgedResponse response = esClient.indices().delete(request,RequestOptions.DEFAULT);// 响应状态System.out.println(response.isAcknowledged());

        esClient.close();}}

3:索引创建好后我们需要将索引里面插入文档数据,包过数据的查询删除等等操作

3.1:将数据插入索引:

IndexRequest

响应:

esClient.index

3.1.1:首先建立一个实体类存放我们要插入的数据类:User请添加图片描述

#3.1.2:然后向对应的索引中插入数据:这里的步骤分三步:

(1):new出索引,并指向我们要插入数据的索引:

request.index("user").id("1001");

请添加图片描述

(2):将数据插入到实体类,并要穿换成json格式:

请添加图片描述

(3):默认响应:

IndexResponse

esClient.index
IndexResponse response = esClient.index(request,RequestOptions.DEFAULT);
packagecom.atguigu.es.test;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.apache.http.HttpHost;importorg.elasticsearch.action.index.IndexRequest;importorg.elasticsearch.action.index.IndexResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.client.indices.GetIndexRequest;importorg.elasticsearch.client.indices.GetIndexResponse;importorg.elasticsearch.common.xcontent.XContentType;publicclassESTest_Doc_Insert{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 插入数据IndexRequest request =newIndexRequest();
        request.index("user").id("1001");User user =newUser();
        user.setName("zhangsan");
        user.setAge(30);
        user.setSex("男");// 向ES插入数据,必须将数据转换位JSON格式ObjectMapper mapper =newObjectMapper();String userJson = mapper.writeValueAsString(user);
        request.source(userJson,XContentType.JSON);IndexResponse response = esClient.index(request,RequestOptions.DEFAULT);System.out.println(response.getResult());

        esClient.close();}}

3.2:修改索引中数据:

UpdateRequest

响应:

esClient.update

修改索引中的数据:跟上面类似,还是要先定位到哪个索引然后进行修改:

packagecom.atguigu.es.test;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.apache.http.HttpHost;importorg.elasticsearch.action.index.IndexRequest;importorg.elasticsearch.action.index.IndexResponse;importorg.elasticsearch.action.update.UpdateRequest;importorg.elasticsearch.action.update.UpdateResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.common.xcontent.XContentType;publicclassESTest_Doc_Update{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 修改数据UpdateRequest request =newUpdateRequest();
        request.index("user").id("1001");
        request.doc(XContentType.JSON,"sex","女");UpdateResponse response = esClient.update(request,RequestOptions.DEFAULT);System.out.println(response.getResult());

        esClient.close();}}

3.3:查询索引中的数据:

GetRequest

响应:

esClient.get
packagecom.atguigu.es.test;importorg.apache.http.HttpHost;importorg.elasticsearch.action.get.GetRequest;importorg.elasticsearch.action.get.GetResponse;importorg.elasticsearch.action.update.UpdateRequest;importorg.elasticsearch.action.update.UpdateResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.common.xcontent.XContentType;publicclassESTest_Doc_Get{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 查询数据GetRequest request =newGetRequest();
        request.index("user").id("1001");GetResponse response = esClient.get(request,RequestOptions.DEFAULT);System.out.println(response.getSourceAsString());

        esClient.close();}}

3.4:删除索引中的文档(数据):

DeleteRequest

响应:

esClient.delete
packagecom.atguigu.es.test;importorg.apache.http.HttpHost;importorg.elasticsearch.action.delete.DeleteRequest;importorg.elasticsearch.action.delete.DeleteResponse;importorg.elasticsearch.action.get.GetRequest;importorg.elasticsearch.action.get.GetResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;publicclassESTest_Doc_Delete{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));DeleteRequest request =newDeleteRequest();
        request.index("user").id("1001");DeleteResponse response = esClient.delete(request,RequestOptions.DEFAULT);System.out.println(response.toString());

        esClient.close();}}

3.5:批量插入数据:

BulkRequest

响应:

esClient.bulk

相当于就是在一个

BulkRequest

里面包含很多

IndexRequest().index
packagecom.atguigu.es.test;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.apache.http.HttpHost;importorg.elasticsearch.action.bulk.BulkRequest;importorg.elasticsearch.action.bulk.BulkResponse;importorg.elasticsearch.action.index.IndexRequest;importorg.elasticsearch.action.index.IndexResponse;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.common.xcontent.XContentType;publicclassESTest_Doc_Insert_Batch{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 批量插入数据BulkRequest request =newBulkRequest();//        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan", "age",30,"sex","男"));//        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi", "age",30,"sex","女"));//        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu", "age",40,"sex","男"));//        request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "wangwu1", "age",40,"sex","女"));//        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "wangwu2", "age",50,"sex","男"));//        request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "wangwu3", "age",50,"sex","男"));//request.add(new IndexRequest().index("user").id("1007").source(XContentType.JSON, "name", "wangwu44", "age",60,"sex","男"));//request.add(new IndexRequest().index("user").id("1008").source(XContentType.JSON, "name", "wangwu555", "age",60,"sex","男"));
        request.add(newIndexRequest().index("user").id("1009").source(XContentType.JSON,"name","wangwu66666","age",60,"sex","男"));BulkResponse response = esClient.bulk(request,RequestOptions.DEFAULT);System.out.println(response.getTook());System.out.println(response.getItems());

        esClient.close();}}

3.6:批量删除:

BulkRequest

响应:

esClient.bulk

,相当于一个

BulkRequest

里面包含很多

DeleteRequest().index
packagecom.atguigu.es.test;importorg.apache.http.HttpHost;importorg.elasticsearch.action.bulk.BulkRequest;importorg.elasticsearch.action.bulk.BulkResponse;importorg.elasticsearch.action.delete.DeleteRequest;importorg.elasticsearch.action.index.IndexRequest;importorg.elasticsearch.client.RequestOptions;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestHighLevelClient;importorg.elasticsearch.common.xcontent.XContentType;publicclassESTest_Doc_Delete_Batch{publicstaticvoidmain(String[] args)throwsException{RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 批量删除数据BulkRequest request =newBulkRequest();

        request.add(newDeleteRequest().index("user").id("1001"));
        request.add(newDeleteRequest().index("user").id("1002"));
        request.add(newDeleteRequest().index("user").id("1003"));BulkResponse response = esClient.bulk(request,RequestOptions.DEFAULT);System.out.println(response.getTook());System.out.println(response.getItems());

        esClient.close();}}

3.7:全量查询:

SearchRequest

响应:

esClient.search

注意变化:

request.indices("user");

请添加图片描述

RestHighLevelClient esClient =newRestHighLevelClient(RestClient.builder(newHttpHost("localhost",9200,"http")));// 1. 查询索引中全部的数据SearchRequest request =newSearchRequest();
        request.indices("user");

        request.source(newSearchSourceBuilder().query(QueryBuilders.matchAllQuery()));SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.8:条件查询:与全量查询变化:

QueryBuilders.termQuery("age", 30)
// 2. 条件查询 : termQuerySearchRequest request =newSearchRequest();
        request.indices("user");

        request.source(newSearchSourceBuilder().query(QueryBuilders.termQuery("age",30)));SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.9:分页查询

builder.from(2); builder.size(2);
3. 分页查询
        SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder().query(QueryBuilders.matchAllQuery());// (当前页码-1)*每页显示数据条数
        builder.from(2);
        builder.size(2);
        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.10:查询排序:

builder.sort("age", SortOrder.DESC);
// 4. 查询排序SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder().query(QueryBuilders.matchAllQuery());//
        builder.sort("age",SortOrder.DESC);

        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.11:过滤字段

builder.fetchSource(includes, excludes);
// 5. 过滤字段SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder().query(QueryBuilders.matchAllQuery());//String[] excludes ={"age"};String[] includes ={};
        builder.fetchSource(includes, excludes);

        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.12:组合查询 :

     // 6. 组合查询
        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //boolQueryBuilder.must(QueryBuilders.matchQuery("age", 30));
        //boolQueryBuilder.must(QueryBuilders.matchQuery("sex", "男"));
        //boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "男"));
        boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30));
        boolQueryBuilder.should(QueryBuilders.matchQuery("age", 40));

        builder.query(boolQueryBuilder);

        request.source(builder);
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();

        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());for( SearchHit hit : hits ){
            System.out.println(hit.getSourceAsString());}

3.13:范围查询 :

QueryBuilders.rangeQuery("age");
SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder();RangeQueryBuilder rangeQuery =QueryBuilders.rangeQuery("age");

        rangeQuery.gte(30);
        rangeQuery.lt(50);

        builder.query(rangeQuery);

        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.14:模糊查询:

QueryBuilders.fuzzyQuery("name","wangwu").fuzziness(Fuzziness.TWO)

Fuzziness.TWO:意思就是字符差两个就可以查出来,代表模糊的范围

SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder();
        builder.query(QueryBuilders.fuzzyQuery("name","wangwu").fuzziness(Fuzziness.TWO));

        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.15:高亮查询:

SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder();TermsQueryBuilder termsQueryBuilder =QueryBuilders.termsQuery("name","zhangsan");HighlightBuilder highlightBuilder =newHighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");

        builder.highlighter(highlightBuilder);
        builder.query(termsQueryBuilder);

        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.16:聚合查询:(求最大最小)对age字段取最大:maxAge

SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder();AggregationBuilder aggregationBuilder =AggregationBuilders.max("maxAge").field("age");
        builder.aggregation(aggregationBuilder);

        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

3.17:分组查询 terms(“ageGroup”).field(“age”);: 根据年龄分组

SearchRequest request =newSearchRequest();
        request.indices("user");SearchSourceBuilder builder =newSearchSourceBuilder();AggregationBuilder aggregationBuilder =AggregationBuilders.terms("ageGroup").field("age");
        builder.aggregation(aggregationBuilder);

        request.source(builder);SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);SearchHits hits = response.getHits();System.out.println(hits.getTotalHits());System.out.println(response.getTook());for(SearchHit hit : hits ){System.out.println(hit.getSourceAsString());}

本文转载自: https://blog.csdn.net/justleavel/article/details/128064927
版权归原作者 water-之 所有, 如有侵权,请联系我们删除。

“ElasticSearch中基础API操作”的评论:

还没有评论