数据准备
ElasticSearch 实现分词全文检索 - 测试数据准备
ElasticSearch的各种查询
不会对查询关键字进行分词
term 查询
term的查询是代表完全匹配,搜索之前不会对你搜索的关键字进行分词,对你的关键字去文档分词库中的去匹配内容
# term 查询 -- 完整匹配 POST /sms-logs-index/_search { "from":0, "size":5, //获取5条,类似分页 "query":{ "term": { "province": { "value": "江苏" } } } }
返回值
{ "took" : 1, //执行花了ms "timed_out" : false, //没有超时 "_shards" : { "total" : 1, //总共多少分片 "successful" : 1, //成功了多少分片 "skipped" : 0, "failed" : 0 }, "hits" : { //hits 中是我们要看的数据 "total" : { "value" : 10, //一共查了N条 "relation" : "eq" }, "max_score" : 0.046520013, //匹配程度,匹配度越高,分数越高 "hits" : [ { "_index" : "sms-logs-index", "_type" : "_doc", "_id" : "Q5XEloYBGlLaT58Lnwjj", "_score" : 0.046520013, "_source" : { //完成内容 "corpName" : "corpName1", "createDate" : "2023-02-28 14:45:14", "fee" : 47, "ipAddr" : "172.16.0.66", "longCode" : "张三1", "mobile" : "13845591752", "operatorld" : 1, "province" : "江苏", "sendDate" : "2023-02-28 14:43:14", "smsContent" : "【阿里云】尊敬的vipsoft:您有2台云服务器ECS配置升级成功。如有CPU、内存变更或0Mbps带宽升级,您需要在ECS控制台手动重启云服务器后才能生效。", "state" : 1 } },
SpringBoot 代码term查询
@Test void termQuery() throws Exception{ String indexName = "sms-logs-index"; RestHighLevelClient client = ESClient.getClient(); //1. 创建Request对象 SearchRequest request = new SearchRequest(indexName); //2. 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.from(0); builder.size(5); builder.query(QueryBuilders.termQuery("province","江苏")); request.source(builder); //3. 执行查询 SearchResponse resp = client.search(request, RequestOptions.DEFAULT); //4. 获取到 _source 中的数据,并展示 for (SearchHit hit : resp.getHits().getHits()) { Map<String, Object> result = hit.getSourceAsMap(); System.out.println(result); } }
terms 查询
terms和term的查询机制是一样,都不会将指定的查询关键字进行分词,直接去分词库中匹配,找到相应文档内容。
terms是在针对一个字段包含多个值的时候使用。
term: where province = 江苏
terms: where province = 江苏 or province = ? or province = ?
Restful
# terms 查询 POST /sms-logs-index/_search { "query":{ "terms": { "province": [ "江苏", "上海" ] } } }
Java
@Test void termsQuery() throws Exception{ String indexName = "sms-logs-index"; RestHighLevelClient client = ESClient.getClient(); //1. 创建Request对象 SearchRequest request = new SearchRequest(indexName); //2. 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.termsQuery("province","江苏","上海")); request.source(builder); //3. 执行查询 SearchResponse resp = client.search(request, RequestOptions.DEFAULT); //4. 获取到 _source 中的数据,并展示 for (SearchHit hit : resp.getHits().getHits()) { Map<String, Object> result = hit.getSourceAsMap(); System.out.println(result); } }
在线ik分词器:https://www.sojson.com/analyzer