当前位置: 首页 > 工具软件 > QueryBuilder > 使用案例 >

Elasticsearch java api 常用查询方法QueryBuilder构造举例

卫学真
2023-12-01

Elasticsearch java api 常用查询方法QueryBuilder构造举例

环境

Elasticsearch版本

5.1.1

pom

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.1.1</version>
</dependency>
 
 

Elasticsearch索引方式

数字

{
    "type": "long"
}
 
 

字符串

{
    "type": "text",
    "fields": {
        "keyword": {
            "type": "keyword",
            "ignore_above": 256
        }
    }
}
 
 

精确查询

以下字段名用${fieldName}代替,具体值用${fieldValue}代替

数字

单个

QueryBuilder qb1 = QueryBuilders.termQuery("${fieldName}", "${fieldValue}");
 
 

批量

QueryBuilder qb1 = QueryBuilders.termsQuery("${fieldName}", "${fieldValues}");
 
 

字符串

单个

QueryBuilder qb1 = QueryBuilders.termQuery("${fieldName}.keyword", "${fieldValue}");
 
 

批量

QueryBuilder qb1 = QueryBuilders.termsQuery("${fieldName}.keyword", "${fieldValues}");
 
 

模糊查询

数字

数字查询都为精确查询

字符串

QueryBuilder qb1 = QueryBuilders.moreLikeThisQuery(new String[]{"${fieldName}"}, new String[]{"${fieldValue}"}, null);
 
 

范围查询

数字

闭区间查询

QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").from(${fieldValue1}).to(${fieldValue2});
 
 

开区间查询

QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").from(${fieldValue1}, false).to(${fieldValue2}, false);
 
 

大于

QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").gt(${fieldValue});
 
 

大于等于

QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").gte(${fieldValue});
 
 

小于

QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").lt(${fieldValue});
 
 

小于等于

QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").lte(${fieldValue});
 
 

多条件查询

QueryBuilder qb1 = QueryBuilders.moreLikeThisQuery(new String[]{"${fieldName1}"}, new String[]{"${fieldValue1}"}, null);
QueryBuilder qb2 = QueryBuilders.rangeQuery("${fieldName2}").gt("${fieldValue2}");
QueryBuilder qb3 = QueryBuilders.boolQuery().must(qb1).must(qb2);
 
 

以上为常用总结,最全最权威请参看官方文档
经验总结,如有错误,请批评指出。

 类似资料: