elasticsearch中Term Query关键字 和ID 的查询方式

elasticsearch中Term Query的查询方式(测试)

  • Term Query为精确查询
    • 根据id精确匹配

Term Query为精确查询

个人测试记录

特别注意的是:Term Query为精确查询,在搜索时会整体匹配关键字,不再将关键字分词。多用于姓名查询

postman工具测试:
举例:
发送:post http://localhost:9200/索引库名/doc/_search
查询name为spring的关键词
{
“query”: {
“term” : {
“name”: “spring”
}
},
“_source” : [“name”,“studymodel”]
}

注意:6.0之前的版本有type(类型)概念,type相当于关系数据库的表,ES官方将在ES9.0版本中彻底删除type。本次测试type直接随便设置一个无意义的名字doc.

  1. Java代码实现

    //搜索请求对象
    SearchRequest searchRequest = new SearchRequest(“xc_course”);
    //设置类型
    searchRequest.types(“doc”);
    //搜索源构建对象
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    //TermQuery
    searchSourceBuilder.query(QueryBuilders.termQuery(“name”,“spring”));
    //source源字段过虑
    searchSourceBuilder.fetchSource(new String[]{“name”,“studymodel”,“price”,“timestamp”},new String[]{});
    //设置搜索源
    searchRequest.source(searchSourceBuilder);
    //执行搜索
    SearchResponse searchResponse = client.search(searchRequest);
    //获取内容
    SearchHits hits = searchResponse .getHits();

根据id精确匹配

{
“query”: {
“ids” : {
“type” : “doc”,
“values” : [“3”, “4”, “100”]
}
}
}

通过termsQuery进行查询,代码如下:

//搜索请求对象
SearchRequest searchRequest = new SearchRequest(“xc_course”);
//设置类型
searchRequest.types(“doc”);
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//主键
String[] ids = new String[]{“1”,“2”};
searchSourceBuilder.query(QueryBuilders.termsQuery("_id", ids));
//source源字段过虑
searchSourceBuilder.fetchSource(new String[]{“name”,“studymodel”,“price”,“timestamp”},new String[]{});
//设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索
SearchResponse searchResponse = client.search(searchRequest);

**大坑大坑 关键字查询和ID查询的Api termQuery termsQuery **

你可能感兴趣的:(elasticsearch)