21 Rest高级客户端实践(七):一个小案例

文章目录

1 准备

  1. 之前的索引
PUT books
{
  "settings": {
    "number_of_shards": 3, 
    "number_of_replicas": 1
  }, 
  "mappings": {
      "properties": {
        "id":{
          "type": "long"
        },
        "title":{
          "type": "text",
          "analyzer": "ik_max_word"
        },
        "language":{
          "type": "keyword"
        },
        "author":{
          "type": "keyword"
        },
        "price":{
          "type": "double"
        },
        "publish_time":{
          "type": "date",
          "format": "yyyy-MM-dd"
        },
        "description":{
          "type": "text",
          "analyzer": "ik_max_word"
        }
      }
    }
  
}

  1. 数据如下
    在这里插入图片描述

  2. 构造这么一个查询,这里就不关心结果了,主要是如何使用java API构造这个一个请求

GET books/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "author": "张若愚"
          }
        }
      ],
      "must": [
        {
          "fuzzy": {
            "title": "python"
          }
        }
      ],
      "must_not": [
        {
          "prefix": {
            "language": {
              "value": "j"
            }
          }
        }
      ], 
      "should": [
        {
         "range": {
           "price": {
             "gte": 0,
             "lte": 100
           }
         }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "title": {}
    }
  },
  "_source": 
  {
    "excludes": ["id","publish_time"]
  },
  "suggest": {
    "my_suggest": {
      "text": "python",
      "term": {
        "field": "description"
      }
    }
  },
  "sort": [
    {
      "price": {
        "order": "desc"
      }
    }
  ]
}
  1. 上面请求的结果
{
  "took" : 5,
  "timed_out" : false,
  "_shards" : {
    "total" : 3,
    "successful" : 3,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
        "_index" : "books",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : null,
        "_source" : {
          "author" : "张若愚",
          "price" : 81.4,
          "description" : "零基础学python,光盘中作者独家整合开发winPython运行环境,涵盖了Python各个扩展库",
          "language" : "python",
          "title" : "Python科学计算"
        },
        "highlight" : {
          "title" : [
            "<em>Python</em>科学计算"
          ]
        },
        "sort" : [
          81.4
        ]
      }
    ]
  },
  "suggest" : {
    "my_suggest" : [
      {
        "text" : "python",
        "offset" : 0,
        "length" : 6,
        "options" : [ ]
      }
    ]
  }
}

2 编码

package study.wyy.esclient.high;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

/**
 * @author wyaoyao
 * @description
 * @date 2021/1/8 15:30
 */
public abstract class BaseTest {

    public static RestHighLevelClient client;
    public static ObjectMapper objectMapper;

    static {
        client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        objectMapper = new ObjectMapper();
    }
}

package study.wyy.esclient.high.search;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;
import org.junit.Test;
import study.wyy.esclient.high.BaseTest;

import java.io.IOException;

/**
 * @author wyaoyao
 * @description
 * @date 2021/1/13 14:17
 */
@Slf4j
public class SearchTest extends BaseTest {

    @Test
    public void test() throws IOException {
        // 1 构建SearchRequest
        SearchRequest request = buildSearchRequest();
        // 2 执行请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        log.info(new ObjectMapper().writer().writeValueAsString(response));

    }

    private SearchRequest buildSearchRequest() {
        SearchRequest request = new SearchRequest();
        // 设置要搜索的索引
        request.indices("books");
        // 添加搜索条件,大多数搜索参数都是通过SearchSourceBuilder构建
        // 构建SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 设置一些基本参数,超时时间,分页信息(from size)等
        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(10));
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10);
        // 构建查询参数
        QueryBuilder queryBuilder = buildQueryParam();
        searchSourceBuilder.query(queryBuilder);

        // 设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        // title字段高亮
        HighlightBuilder.Field title = new HighlightBuilder.Field("title");
        highlightBuilder.field(title);
        searchSourceBuilder.highlighter(highlightBuilder);

        // 设置Suggest
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        TermSuggestionBuilder text = SuggestBuilders.termSuggestion("description").text("python");
        suggestBuilder.addSuggestion("my_suggest",text);
        searchSourceBuilder.suggest(suggestBuilder);

        // source过滤
        String[] excludes = {"id","publish_time"};
        searchSourceBuilder.fetchSource(null,excludes);

        // 排序
        FieldSortBuilder sortBuilder = new FieldSortBuilder("price").order(SortOrder.DESC);
        searchSourceBuilder.sort(sortBuilder);

        // 最后不要忘记将searchSourceBuilder添加到SearchRequest
        request.source(searchSourceBuilder);
        return request;
    }

    private QueryBuilder buildQueryParam() {
        QueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                // 过滤
                .filter(QueryBuilders.termQuery("author", "张若愚"))
                // 模糊查询
                .must(QueryBuilders.fuzzyQuery("title", "python"))
                // 前缀查询
                .mustNot(QueryBuilders.prefixQuery("language", "j"))
                // 范围查询
                .should(QueryBuilders.rangeQuery("price").gte(0).lte(100));
        return boolQueryBuilder;
    }
}

最后的输出

{
    "internalResponse":{
        "numReducePhases":1,
        "fragment":true
    },
    "scrollId":null,
    "totalShards":3,
    "successfulShards":3,
    "skippedShards":0,
    "shardFailures":[

    ],
    "clusters":{
        "total":0,
        "successful":0,
        "skipped":0,
        "fragment":true
    },
    "profileResults":{

    },
    "numReducePhases":1,
    "terminatedEarly":null,
    "aggregations":null,
    "timedOut":false,
    "took":{
        "hours":0,
        "minutes":0,
        "seconds":0,
        "nanos":12000000,
        "millis":12,
        "stringRep":"12ms",
        "micros":12000,
        "minutesFrac":0.0002,
        "hoursFrac":0.0000033333333333333333,
        "days":0,
        "microsFrac":12000,
        "daysFrac":0.00000013888888888888888,
        "millisFrac":12,
        "secondsFrac":0.012
    },
    "suggest":{
        "fragment":true
    },
    "failedShards":0,
    "hits":{
        "hits":[
            {
                "score":"NaN",
                "id":"3",
                "type":"_doc",
                "nestedIdentity":null,
                "version":-1,
                "seqNo":-2,
                "primaryTerm":0,
                "highlightFields":{
                    "title":{
                        "name":"title",
                        "fragments":[
                            {
                                "fragment":true
                            }
                        ],
                        "fragment":true
                    }
                },
                "sortValues":[
                    81.4
                ],
                "matchedQueries":[

                ],
                "explanation":null,
                "shard":null,
                "index":"books",
                "clusterAlias":null,
                "sourceAsMap":{
                    "author":"张若愚",
                    "price":81.4,
                    "description":"零基础学python,光盘中作者独家整合开发winPython运行环境,涵盖了Python各个扩展库",
                    "language":"python",
                    "title":"Python科学计算"
                },
                "innerHits":null,
                "fields":{

                },
                "sourceRef":{
                    "fragment":true
                },
                "rawSortValues":[

                ],
                "sourceAsString":"{"author":"张若愚","price":81.4,"description":"零基础学python,光盘中作者独家整合开发winPython运行环境,涵盖了Python各个扩展库","language":"python","title":"Python科学计算"}",
                "fragment":false
            }
        ],
        "totalHits":{
            "value":1,
            "relation":"EQUAL_TO"
        },
        "maxScore":"NaN",
        "sortFields":null,
        "collapseField":null,
        "collapseValues":null,
        "fragment":true
    },
    "fragment":false
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值