数据准备
ElasticSearch 实现分词全文检索 - 测试数据准备
bool查询
复合过滤器,将多个查询条件,以一定的逻辑组合在一起
- must:所有的条件,用 must 组合在一起,标识 and 的意思
- must_not: 将 must_not 中的条件,全部都不能匹配,标识 not 的意思
- should: 所有的条件,用should组合在一起,表示 or 的意思
# 查询省份为江苏或上海 # operatorld 不是联通 !=2 # smsContent 中包括 开心 和 钞票 # bool 查询 POST /sms-logs-index/_search { "query": { "bool": { "should": [ {"term": { "province": { "value": "江苏" } }}, {"term": { "province": { "value": "上海" } }} ], "must_not": [ { "term": { "operatorld": { "value": "2" } } } ], "must": [ { "match": { "smsContent": "开心" } }, { "match": { "smsContent": "钞票" } } ] } } }
JAVA
@Test void boolQuery() throws Exception { String indexName = "sms-logs-index"; RestHighLevelClient client = ESClient.getClient(); //1. 创建SearchRequest对象 SearchRequest request = new SearchRequest(indexName); //2. 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.should(QueryBuilders.termQuery("province","江苏")); boolQuery.should(QueryBuilders.termQuery("province","上海")); boolQuery.mustNot(QueryBuilders.termQuery("operatorld","2")); boolQuery.must(QueryBuilders.matchQuery("smsContent","开心")); boolQuery.must(QueryBuilders.matchQuery("smsContent","钞票")); builder.query(boolQuery); request.source(builder); //3. 执行查询 SearchResponse resp = client.search(request, RequestOptions.DEFAULT); //4. 输出返回值 for (SearchHit hit : resp.getHits().getHits()) { System.out.println(hit.getSourceAsMap()); } }
boosting 查询
boosting 查询可以帮助我们去影响查询后的 score
- positive:只有匹配上positive的查询的内容,才会被放到返回的结果中
- negative:如果匹配上和positive并且也匹配上了negative,就可以降低这样的文档 score.
- negative_boost:指定系数,必须小于 1.0
关于查询时,分数是如何计算的: - 搜索的关键字在文档中出现的频次越高,分数就越高
- 指定的文档内容越短,分数就越高
- 我们在搜索时,指定的关键字也会被分词,这个被分词的内容,被分词库匹配的个数越多,分数越高
POST /sms-logs-index/_search { "query": { "boosting": { "positive": { "match": { "smsContent": "人" } }, "negative": { "match": { "smsContent": "网络" # 如果查出来的包括 网络 } }, "negative_boost": 0.5 #将分数乘以系数 0.5 ,分数越高,排名越靠前 } } }
Java
@Test void boostringQuery() throws Exception { String indexName = "sms-logs-index"; RestHighLevelClient client = ESClient.getClient(); //1. 创建SearchRequest对象 SearchRequest request = new SearchRequest(indexName); //2. 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); BoostingQueryBuilder boostingQuery = QueryBuilders.boostingQuery( QueryBuilders.matchQuery("smsContent", "人"), QueryBuilders.matchQuery("smsContent", "网络") ).negativeBoost(0.5f); builder.query(boostingQuery); request.source(builder); //3. 执行查询 SearchResponse resp = client.search(request, RequestOptions.DEFAULT); //4. 输出返回值 for (SearchHit hit : resp.getHits().getHits()) { System.out.println(hit.getSourceAsMap()); } }