• 详解 ElasticSearch 基础教程


    1. 🌹 ElasticSearch 基础教程,请指教。
    2. 🌹🌹 如你对技术也感兴趣,欢迎交流。
    3. 🌹🌹🌹 如有对阁下帮助,请👍点赞💖收藏🐱‍🏍分享😀

    理论

    Elasticsearch: The Official Distributed Search & Analytics Engine | ElasticElasticsearch is the leading distributed, RESTful, free and open search and analytics engine designed for speed, horizontal scalability, reliability, and easy management. Get started for free.icon-default.png?t=N7T8https://www.elastic.co/elasticsearch/

            Elasticsearch是基于Apache Lucene的搜索服务器它的最新版本是8.10.2。

            Elasticsearch是一个实时的分布式开放源代码全文本搜索和分析引擎。可从RESTful Web服务界面访问它,并使用无模式的JSON(JavaScript对象表示法)文档存储数据。它基于Java编程语言构建,因此Elasticsearch可以在不同平台上运行。它使用户能够以很高的速度浏览大量的数据。

    Elasticsearch & MYSQL 

    索引 

     对比关系型数据库,创建索引就等同于创建数据库

    创建 

    PUT /shopping
    HTTP 的 PUT 请求

     

    查看

     单个索引 

    GET /shopping
    HTTP 的 GET 请求

    全部索引 

    GET /_cat/indices?v
    HTTP 的 GET 请求

    删除 

    DELETE /shopping
    HTTP 的 DELETE 请求

     文档

    创建

     随机ID

    1. POST /shopping/_doc
    2. {
    3. "title":"华为meta60pro",
    4. "category":"手机",
    5. "images":"https://www.gulixueyuan.com/xm.jpg",
    6. "price":"6499.00"
    7. }

     自定义ID

    1. POST /shopping/_doc/1000
    2. {
    3. "title":"华为meta60pro max",
    4. "category":"手机",
    5. "images":"https://www.gulixueyuan.com/xm.jpg",
    6. "price":"7499.00"
    7. }
    8. PUT /shopping/_doc/1002
    9. {
    10. "title":"华为meta60pro max尊享",
    11. "category":"手机",
    12. "images":"https://www.gulixueyuan.com/xm.jpg",
    13. "price":"8499.00"
    14. }

    查询

     主键查询

     不存在查询

    全部查询

    GET /shopping/_search

    修改

    全量更新 

    1. PUT /shopping/_doc/1002
    2. {
    3. "title":"华为meta60pro max尊享",
    4. "category":"手机",
    5. "images":"https://www.gulixueyuan.com/xm.jpg",
    6. "price":"12999.00"
    7. }
    修改

    修改后

     局部更新

    1. POST /shopping/_update/1002
    2. {
    3. "doc":{
    4. "title":"华为meta70pro max尊享"
    5. }
    6. }

     删除

    DELETE /shopping/_doc/1000

    复杂查询

    请求路径方式

    GET /shopping/_search?q=category:手机

     请求体方式

    属性查询 
    1. GET /shopping/_search
    2. {
    3. "query":{
    4. "match": {
    5. "category": "手机"
    6. }
    7. }
    8. }
     全量查询
    1. GET /shopping/_search
    2. {
    3. "query":{
    4. "match_all": {}
    5. }
    6. }

    分页查询 
    1. GET /shopping/_search
    2. {
    3. "query":{
    4. "match_all": {}
    5. },
    6. "from": 1,
    7. "size": 2
    8. }

    指定返回属性
    1. GET /shopping/_search
    2. {
    3. "query":{
    4. "match_all": {}
    5. },
    6. "from": 1,
    7. "size": 2,
    8. "_source": ["price","title"]
    9. }
     排序
    1. GET /shopping/_search
    2. {
    3. "query":{
    4. "match_all": {}
    5. },
    6. "from": 1,
    7. "size": 2,
    8. "_source": ["title"],
    9. "sort": [
    10. {
    11. "title": {
    12. "order": "desc"
    13. }
    14. }
    15. ]
    16. }
    错误

    1. # 设置属性类型
    2. PUT shopping/_mapping
    3. {
    4. "properties": {
    5. "price": {
    6. "type": "text"
    7. },
    8. "title": {
    9. "fielddata": true,
    10. "type": "text"
    11. }
    12. }
    13. }
    查询结果

     组合查询

     同时满足所有条件

    1. ## SQL: category="手机" AND price="6499.00"
    2. GET /shopping/_search
    3. {
    4. "query":{
    5. "bool": {
    6. "must": [
    7. {
    8. "match": {
    9. "category": "手机"
    10. }
    11. },
    12. {
    13. "match": {
    14. "price": "6499.00"
    15. }
    16. }
    17. ]
    18. }
    19. }
    20. }

    满足某个条件

    1. ## SQL: category="手机" OR price="6499.00"
    2. GET /shopping/_search
    3. {
    4. "query":{
    5. "bool": {
    6. "should": [
    7. {
    8. "match": {
    9. "category": "手机"
    10. }
    11. },
    12. {
    13. "match": {
    14. "price": "6499.00"
    15. }
    16. }
    17. ]
    18. }
    19. }
    20. }

    范围查询

    1. ## SQL: (category="手机" OR price=6499.00) and (price between 6500 and 10000)
    2. GET /shopping/_search
    3. {
    4. "query":{
    5. "bool": {
    6. "should": [
    7. {
    8. "match": {
    9. "category": "手机"
    10. }
    11. },
    12. {
    13. "match": {
    14. "price": 6499.00
    15. }
    16. }
    17. ],
    18. "filter": {
    19. "range": {
    20. "price": {
    21. "gt": 6500,
    22. "lt": 10000
    23. }
    24. }
    25. }
    26. }
    27. }
    28. }

    分页排序

    1. # SQL: (category="手机" OR price=6499.00) and (price between 6500 and 10000) limit 2 order by price desc
    2. GET /shopping/_search
    3. {
    4. "query":{
    5. "bool": {
    6. "should": [
    7. {
    8. "match": {
    9. "category": "手机"
    10. }
    11. },
    12. {
    13. "match": {
    14. "price": 6499.00
    15. }
    16. }
    17. ],
    18. "filter": {
    19. "range": {
    20. "price": {
    21. "gt": 6500,
    22. "lt": 10000
    23. }
    24. }
    25. }
    26. }
    27. },
    28. "from": 0,
    29. "size": 2,
    30. "sort": [
    31. {
    32. "price": {
    33. "order": "desc"
    34. }
    35. }
    36. ]
    37. }

     高亮显示

    1. GET /shopping/_search
    2. {
    3. "query":{
    4. "match_phrase": {
    5. "category": "手机"
    6. }
    7. },
    8. "highlight": {
    9. "fields": {
    10. "category": {}
    11. }
    12. }
    13. }

    聚合查询 

    分组聚合 

    1. GET /shopping/_search
    2. {
    3. "aggs": {
    4. "cacl_avg": {
    5. "terms": {
    6. "field":"price"
    7. }
    8. }
    9. },
    10. "size": 0
    11. }

     计算平均值

    1. GET /shopping/_search
    2. {
    3. "aggs": {
    4. "cacl_avg": {
    5. "avg": {
    6. "field":"price"
    7. }
    8. }
    9. },
    10. "size": 0
    11. }

    创建映射关系

    映射关系 

    1. PUT /user/_mapping
    2. {
    3. "properties": {
    4. "user":{
    5. "type": "text",
    6. "index": true
    7. },
    8. "sex":{
    9. "type": "keyword",
    10. "index": false
    11. },
    12. "tel":{
    13. "type": "keyword",
    14. "index": true
    15. }
    16. }
    17. }

    数据 

    分词查询(type=text)

    关键字查询 (type=keyword)

    未被索引,不允许查询 

     总结

    type=text ,index=true 时,可分词可查询;

    type=keyword ,index=true 时,不可分词可查询;

    index=false 时,不可查询

     Java API

     Maven

    1. <dependency>
    2. <groupId>org.elasticsearch</groupId>
    3. <artifactId>elasticsearch</artifactId>
    4. <version>7.8.0</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.elasticsearch.client</groupId>
    8. <artifactId>elasticsearch-rest-high-level-client</artifactId>
    9. <version>7.8.0</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>org.apache.logging.log4j</groupId>
    13. <artifactId>log4j-api</artifactId>
    14. <version>2.17.2</version>
    15. </dependency>
    16. <dependency>
    17. <groupId>org.apache.logging.log4j</groupId>
    18. <artifactId>log4j-core</artifactId>
    19. <version>2.17.2</version>
    20. </dependency>
    21. <dependency>
    22. <groupId>cn.hutool</groupId>
    23. <artifactId>hutool-all</artifactId>
    24. <version>5.8.18</version>
    25. </dependency>

     客户端

    1. public class ElasticSearchClient {
    2. /**
    3. * 创建对象
    4. *
    5. * @param host 地址
    6. * @param port 端口
    7. */
    8. public static RestHighLevelClient getElasticSearchClient() {
    9. String host="127.0.0.1";
    10. int port=9200;
    11. String scheme="http";
    12. return new RestHighLevelClient(
    13. RestClient.builder(new HttpHost(host, port,scheme)));
    14. }
    15. /**
    16. * 关闭
    17. *
    18. * @param client 客户端对象
    19. */
    20. public static void closeClient(RestHighLevelClient client) {
    21. try {
    22. client.close();
    23. } catch (IOException e) {
    24. throw new RuntimeException(e);
    25. }
    26. }

     创建索引

    1. /**
    2. * 创建索引
    3. *
    4. * @param index 索引名
    5. * RestHighLevelClient restHighLevelClient = ElasticSearchClient.getElasticSearchClient();
    6. */
    7. public static void createIndex(RestHighLevelClient restHighLevelClient, String index) {
    8. try {
    9. //创建索引
    10. CreateIndexRequest request = new CreateIndexRequest(index);
    11. CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    12. boolean acknowledged = createIndexResponse.isAcknowledged();
    13. System.out.println("索引操作:" + acknowledged);
    14. } catch (IOException e) {
    15. throw new RuntimeException(e);
    16. }
    17. }

     ​​​测试

    查询索引 

    1. /**
    2. * 查询索引
    3. *
    4. * @param index 索引名
    5. */
    6. public static void findIndex(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. GetIndexRequest request = new GetIndexRequest(index);
    10. GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
    11. System.out.println("------------------------------------------------");
    12. System.out.println(getIndexResponse.getAliases());
    13. System.out.println(getIndexResponse.getMappings());
    14. System.out.println(getIndexResponse.getSettings());
    15. System.out.println("------------------------------------------------");
    16. } catch (IOException e) {
    17. throw new RuntimeException(e);
    18. }
    19. }

     测试

    删除索引

    1. /**
    2. * 删除索引
    3. *
    4. * @param index 索引名
    5. */
    6. public static void deleteIndex(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. DeleteIndexRequest request = new DeleteIndexRequest(index);
    10. AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
    11. System.out.println("------------------------------------------------");
    12. System.out.println(response.isAcknowledged());
    13. System.out.println("------------------------------------------------");
    14. } catch (IOException e) {
    15. throw new RuntimeException(e);
    16. }
    17. }

    测试 

    文档 

    创建文档 

    1. /**
    2. * 创建文档
    3. *
    4. * @param index 索引
    5. * @param id id
    6. * @param source Json对象
    7. */
    8. public static void addDoc(RestHighLevelClient restHighLevelClient, String index, String id, Object source) {
    9. try {
    10. //创建索引
    11. IndexRequest indexRequest = new IndexRequest();
    12. indexRequest.index(index).id(id);
    13. indexRequest.source(JSONUtil.toJsonPrettyStr(source), XContentType.JSON);
    14. IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    15. System.out.println("------------------------------------------------");
    16. System.out.println(indexResponse.status());
    17. System.out.println("------------------------------------------------");
    18. } catch (IOException e) {
    19. throw new RuntimeException(e);
    20. }
    21. }

     测试

    修改文档

    1. /**
    2. * 修改数据
    3. *
    4. * @param index 索引
    5. * @param id id
    6. * @param source Json对象
    7. */
    8. public static void updateDoc(RestHighLevelClient restHighLevelClient, String index, String id, Map<String, Object> source) {
    9. try {
    10. //创建索引
    11. UpdateRequest request = new UpdateRequest();
    12. request.index(index).id(id);
    13. request.doc(source, XContentType.JSON);
    14. UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
    15. System.out.println("------------------------------------------------");
    16. System.out.println(response.status());
    17. System.out.println("------------------------------------------------");
    18. } catch (IOException e) {
    19. throw new RuntimeException(e);
    20. }
    21. }

     查询文档

    1. /**
    2. * 查询数据
    3. *
    4. * @param index 索引
    5. * @param id id
    6. */
    7. public static void findDoc(RestHighLevelClient restHighLevelClient, String index, String id) {
    8. try {
    9. //创建索引
    10. GetRequest request = new GetRequest();
    11. request.index(index).id(id);
    12. GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
    13. System.out.println("------------------------------------------------");
    14. System.out.println(getResponse.getSourceAsString());
    15. System.out.println("------------------------------------------------");
    16. } catch (IOException e) {
    17. throw new RuntimeException(e);
    18. }
    19. }

     删除文档

    1. /**
    2. * 查询数据
    3. *
    4. * @param index 索引
    5. * @param id id
    6. */
    7. public static void delDoc(RestHighLevelClient restHighLevelClient, String index, String id) {
    8. try {
    9. //创建索引
    10. DeleteRequest request = new DeleteRequest();
    11. request.index(index).id(id);
    12. DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
    13. System.out.println("------------------------------------------------");
    14. System.out.println(response.getResult());
    15. System.out.println("------------------------------------------------");
    16. } catch (IOException e) {
    17. throw new RuntimeException(e);
    18. }
    19. }

    批量文档 

     创建文档

    1. /**
    2. * 创建文档
    3. *
    4. * @param index 索引
    5. * @param id id
    6. * @param sources 数组
    7. */
    8. public static void addDoc(RestHighLevelClient restHighLevelClient, String index, List<String> ids, List<Object> sources) {
    9. try {
    10. //创建索引
    11. BulkRequest request = new BulkRequest();
    12. int size = Math.min(ids.size(), sources.size());
    13. for (int i = 0; i < size; i++) {
    14. request.add(new IndexRequest().index(index).id(ids.get(i)).source(JSONUtil.toJsonPrettyStr(sources.get(i)), XContentType.JSON));
    15. }
    16. BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
    17. System.out.println("------------------------------------------------");
    18. System.out.println(bulk.status());
    19. System.out.println("------------------------------------------------");
    20. } catch (IOException e) {
    21. throw new RuntimeException(e);
    22. }
    23. }

    删除文档 

    1. /**
    2. * 删除数据
    3. *
    4. * @param index 索引
    5. * @param ids id
    6. */
    7. public static void delDoc(RestHighLevelClient restHighLevelClient, String index, List<String> ids) {
    8. try {
    9. //创建索引
    10. BulkRequest request = new BulkRequest();
    11. for (String id : ids) {
    12. request.add(new DeleteRequest().index(index).id(id));
    13. }
    14. BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
    15. System.out.println("------------------------------------------------");
    16. System.out.println(bulk.status());
    17. System.out.println("------------------------------------------------");
    18. } catch (IOException e) {
    19. throw new RuntimeException(e);
    20. }
    21. }

     高级查询

    全量查询

    1. /**
    2. * 全量查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void completeSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
    12. request.source(searchSourceBuilder);
    13. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    14. System.out.println("------------------------------------------------");
    15. System.out.println(response.getHits().getTotalHits());
    16. for (SearchHit hit : response.getHits().getHits()) {
    17. System.out.println(hit.getSourceAsString());
    18. }
    19. System.out.println("------------------------------------------------");
    20. } catch (IOException e) {
    21. throw new RuntimeException(e);
    22. }
    23. }

    测试 

     

    条件查询

    1. /**
    2. * 条件查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void pageSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.termQuery("age", "16"));
    12. request.source(searchSourceBuilder);
    13. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    14. System.out.println("------------------------------------------------");
    15. System.out.println(response.getHits().getTotalHits());
    16. for (SearchHit hit : response.getHits().getHits()) {
    17. System.out.println(hit.getSourceAsString());
    18. }
    19. System.out.println("------------------------------------------------");
    20. } catch (IOException e) {
    21. throw new RuntimeException(e);
    22. }
    23. }

    测试 

     

    分页查询

    1. /**
    2. * 分页查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void pageSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
    12. searchSourceBuilder.from(0);
    13. searchSourceBuilder.size(5);
    14. request.source(searchSourceBuilder);
    15. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    16. System.out.println("------------------------------------------------");
    17. System.out.println(response.getHits().getTotalHits());
    18. for (SearchHit hit : response.getHits().getHits()) {
    19. System.out.println(hit.getSourceAsString());
    20. }
    21. System.out.println("------------------------------------------------");
    22. } catch (IOException e) {
    23. throw new RuntimeException(e);
    24. }
    25. }

    测试

     

    排序查询 

    1. /**
    2. * 排序查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void sortSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
    12. searchSourceBuilder.from(0);
    13. searchSourceBuilder.size(4);
    14. searchSourceBuilder.sort("age", SortOrder.DESC);
    15. request.source(searchSourceBuilder);
    16. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    17. System.out.println("------------------------------------------------");
    18. System.out.println(response.getHits().getTotalHits());
    19. for (SearchHit hit : response.getHits().getHits()) {
    20. System.out.println(hit.getSourceAsString());
    21. }
    22. System.out.println("------------------------------------------------");
    23. } catch (IOException e) {
    24. throw new RuntimeException(e);
    25. }
    26. }

    测试 

     

    返回属性查询

    1. /**
    2. * 过滤查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void filterSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
    12. // 过滤
    13. String[] includes = {"name"};
    14. String[] excludes = {};
    15. searchSourceBuilder.fetchSource(includes, excludes);
    16. // 分页
    17. searchSourceBuilder.from(0);
    18. searchSourceBuilder.size(4);
    19. // 排序
    20. searchSourceBuilder.sort("age", SortOrder.DESC);
    21. request.source(searchSourceBuilder);
    22. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    23. System.out.println("------------------------------------------------");
    24. System.out.println(response.getHits().getTotalHits());
    25. for (SearchHit hit : response.getHits().getHits()) {
    26. System.out.println(hit.getSourceAsString());
    27. }
    28. System.out.println("------------------------------------------------");
    29. } catch (IOException e) {
    30. throw new RuntimeException(e);
    31. }
    32. }

    测试 

     

    组合查询

    1. /**
    2. * 组合查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void combinationSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    12. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    13. // boolQueryBuilder.must(QueryBuilders.matchQuery("age","19"));
    14. // boolQueryBuilder.must(QueryBuilders.matchQuery("name","lisi"));
    15. // boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex","女"));
    16. boolQueryBuilder.should(QueryBuilders.matchQuery("age","19"));
    17. boolQueryBuilder.should(QueryBuilders.matchQuery("age","20"));
    18. searchSourceBuilder.query(boolQueryBuilder);
    19. // 过滤
    20. String[] includes = {"name","age"};
    21. String[] excludes = {};
    22. searchSourceBuilder.fetchSource(includes, excludes);
    23. // 分页
    24. searchSourceBuilder.from(0);
    25. searchSourceBuilder.size(4);
    26. // 排序
    27. searchSourceBuilder.sort("age", SortOrder.DESC);
    28. request.source(searchSourceBuilder);
    29. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    30. System.out.println("------------------------------------------------");
    31. System.out.println(response.getHits().getTotalHits());
    32. for (SearchHit hit : response.getHits().getHits()) {
    33. System.out.println(hit.getSourceAsString());
    34. }
    35. System.out.println("------------------------------------------------");
    36. } catch (IOException e) {
    37. throw new RuntimeException(e);
    38. }
    39. }

    测试

     

     

    范围查询

    1. /**
    2. * 范围查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void rangeSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    12. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    13. RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").gt(16).lt(28);
    14. boolQueryBuilder.filter(rangeQueryBuilder);
    15. searchSourceBuilder.query(boolQueryBuilder);
    16. // 过滤
    17. String[] includes = {"name","age"};
    18. String[] excludes = {};
    19. searchSourceBuilder.fetchSource(includes, excludes);
    20. // 分页
    21. searchSourceBuilder.from(0);
    22. searchSourceBuilder.size(2);
    23. // 排序
    24. searchSourceBuilder.sort("age", SortOrder.DESC);
    25. request.source(searchSourceBuilder);
    26. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    27. System.out.println("------------------------------------------------");
    28. System.out.println(response.getHits().getTotalHits());
    29. for (SearchHit hit : response.getHits().getHits()) {
    30. System.out.println(hit.getSourceAsString());
    31. }
    32. System.out.println("------------------------------------------------");
    33. } catch (IOException e) {
    34. throw new RuntimeException(e);
    35. }
    36. }

    测试

     

    模糊查询

    1. /**
    2. * 模糊查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void vagueSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    12. // 模糊条件
    13. searchSourceBuilder.query(QueryBuilders.fuzzyQuery("name","wangwu").fuzziness(Fuzziness.TWO));
    14. // 过滤
    15. String[] includes = {"name","age"};
    16. String[] excludes = {};
    17. searchSourceBuilder.fetchSource(includes, excludes);
    18. // 分页
    19. searchSourceBuilder.from(0);
    20. searchSourceBuilder.size(2);
    21. // 排序
    22. searchSourceBuilder.sort("age", SortOrder.DESC);
    23. request.source(searchSourceBuilder);
    24. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    25. System.out.println("------------------------------------------------");
    26. System.out.println(response.getHits().getTotalHits());
    27. for (SearchHit hit : response.getHits().getHits()) {
    28. System.out.println(hit.getSourceAsString());
    29. }
    30. System.out.println("------------------------------------------------");
    31. } catch (IOException e) {
    32. throw new RuntimeException(e);
    33. }
    34. }

    测试

    高亮查询

    1. /**
    2. * 高亮查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void highSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    12. // 模糊条件
    13. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangwu");
    14. HighlightBuilder highlightBuilder=new HighlightBuilder();
    15. highlightBuilder.preTags("").postTags("").field("name");
    16. searchSourceBuilder.highlighter(highlightBuilder);
    17. searchSourceBuilder.query(termQueryBuilder);
    18. // 过滤
    19. // String[] includes = {"name","age"};
    20. // String[] excludes = {};
    21. // searchSourceBuilder.fetchSource(includes, excludes);
    22. // 分页
    23. searchSourceBuilder.from(0);
    24. searchSourceBuilder.size(2);
    25. // 排序
    26. searchSourceBuilder.sort("age", SortOrder.DESC);
    27. request.source(searchSourceBuilder);
    28. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    29. System.out.println("------------------------------------------------");
    30. System.out.println(response.getHits().getTotalHits());
    31. for (SearchHit hit : response.getHits().getHits()) {
    32. System.out.println(hit);
    33. }
    34. System.out.println("------------------------------------------------");
    35. } catch (IOException e) {
    36. throw new RuntimeException(e);
    37. }
    38. }

     测试

    聚合查询 

    1. /**
    2. * 聚合查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void polymerizationSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    12. MaxAggregationBuilder maxAggregationBuilder = AggregationBuilders.max("MaxAge").field("age");
    13. searchSourceBuilder.aggregation(maxAggregationBuilder);
    14. request.source(searchSourceBuilder);
    15. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    16. System.out.println("------------------------------------------------");
    17. System.out.println(response.getHits().getTotalHits());
    18. for (Aggregation aggregation : response.getAggregations()) {
    19. System.out.println(JSONUtil.toJsonPrettyStr(aggregation));
    20. }
    21. System.out.println("------------------------------------------------");
    22. } catch (IOException e) {
    23. throw new RuntimeException(e);
    24. }
    25. }

    测试 

     分组查询

    1. /**
    2. * 分组查询
    3. *
    4. * @param index 索引
    5. */
    6. public static void groupSearch(RestHighLevelClient restHighLevelClient, String index) {
    7. try {
    8. //创建索引
    9. SearchRequest request = new SearchRequest();
    10. request.indices(index);
    11. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    12. TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
    13. searchSourceBuilder.aggregation(termsAggregationBuilder);
    14. request.source(searchSourceBuilder);
    15. SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
    16. System.out.println("------------------------------------------------");
    17. System.out.println(response.getHits().getTotalHits());
    18. for (Aggregation aggregation : response.getAggregations()) {
    19. System.out.println(JSONUtil.toJsonPrettyStr(aggregation));
    20. }
    21. System.out.println("------------------------------------------------");
    22. } catch (IOException e) {
    23. throw new RuntimeException(e);
    24. }
    25. }

    测试 

  • 相关阅读:
    新书推荐:人-机器人交互导论
    图像数据通道格式:NCHW和NHWC的区别
    linux网络协议栈源码分析 - 传输层(TCP连接的建立)
    在word文档中找不到endnote的选项卡
    低代码助力企业数字化转型
    回溯 -- 21天学习挑战赛第一天
    华为软件测试笔试真题之变态逻辑推理题【二】华为爆火面试题
    unsupported ssl backend ‘openssl‘. supported ssl backends:gnutls
    《基于FPGA的数字信号处理》专栏的导航与说明
    算法金 | 再见!!!K-means
  • 原文地址:https://blog.csdn.net/qq_32662595/article/details/133713413