ElasticSearch-term&terms查询
Posted 永旗狍子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ElasticSearch-term&terms查询相关的知识,希望对你有一定的参考价值。
目录
一.term&terms查询
1.term查询
term的查询是代表完全匹配,搜索之前不会对你搜索的关键字进行分词,对你的关键字去文档分词库中去匹配内容。
# term查询
POST /sms-logs-index/sms-logs-type/_search
{
"from": 0, # limit ?
"size": 5, # limit x,?
"query": {
"term": {
"province": {
"value": "北京"
}
}
}
}
使用:kibana工具
代码实现方式
/**
* @author: qiuyongqi
* @time: 15:50 2021/6/7
* @description: 创建测试类,连接ES
*/
public class EsClient {
public static RestHighLevelClient getClient(){
// 创建HttpHost对象
HttpHost httpHost = new HttpHost("192.168.247.128",9200);
// 创建RestClientBuilder
RestClientBuilder clientBuilder = RestClient.builder(httpHost);
// 创建RestHighLevelClient
RestHighLevelClient client = new RestHighLevelClient(clientBuilder);
// 返回
return client;
}
}
public class demo4 {
//定义RestHighLevelClient对象
RestHighLevelClient client = EsClient.getClient();
//创建objectMaper对象
ObjectMapper objectMapper = new ObjectMapper();
//定义索引名称
String index = "sms-logs-index";
//定义类型名称
String type = "sms-logs-type";
@Test
public void searchTerm() throws IOException {
//1. 创建Request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
//2. 指定查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.termQuery("province", "北京"));
request.source(builder);
//3. 执行查询
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4. 获取到_source中的数据,并展示
for (SearchHit hit : response.getHits().getHits()) {
System.out.println(hit.getSourceAsMap());
}
}
}
2.terms查询
terms和term的查询机制是一样,都不会将指定的查询关键字进行分词,直接去分词库中匹配,找到相应文档内容。
terms是在针对一个字段包含多个值的时候使用。
- term:where province = 北京;
- terms:where province = 北京 or province = ?or province = ?
# terms查询
POST /sms-logs-index/sms-logs-type/_search
{
"query": {
"terms": {
"province": [
"北京",
"山西",
"武汉"
]
}
}
}
使用:kibana工具
代码实现方式
@Test
public void searchTerms() throws IOException {
//1. 创建request
SearchRequest request=new SearchRequest(index);
request.types(type);
//2. 封装查询条件
SearchSourceBuilder builder=new SearchSourceBuilder();
builder.query(QueryBuilders.termsQuery("province","北京","上海"));
request.source(builder);
//3. 执行查询
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4. 输出_source
for (SearchHit hit : response.getHits().getHits()) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
System.out.println(sourceAsMap);
}
}
需要数据的可以私我哦!
以上是关于ElasticSearch-term&terms查询的主要内容,如果未能解决你的问题,请参考以下文章