这是针对ES查询的一套封装。 因为时间有限仅仅能够支持一些简单查询,但能满足大部分开发需求。
同时也封装了对索引以及数据的CRUD、批量处理。
public static void main(String[] args) {
try {
ElasticSearchService service = new ElasticSearchService("es", "192.168.1.1", 9300);
ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
constructor.must(new ESQueryBuilders().term("gender", "f").range("age", 20, 50));
constructor.should(new ESQueryBuilders().term("gender", "f").range("age", 20, 50).fuzzy("age", 20));
constructor.mustNot(new ESQueryBuilders().term("gender", "m"));
constructor.setSize(15); //查询返回条数,最大 10000
constructor.setFrom(11); //分页查询条目起始位置, 默认0
constructor.setAsc("age"); //排序
List> list = service.search("bank", "account", constructor);
Map map = service.statSearch("bank", "account", constructor, "state");
} catch (Exception e) {
e.printStackTrace();
}
}
条件接口
import org.elasticsearch.index.query.QueryBuilder;
import java.util.List;
public interface ESCriterion {
public enum Operator {
TERM, TERMS, RANGE, FUZZY, QUERY_STRING, MISSING
}
public enum MatchMode {
START, END, ANYWHERE
}
public enum Projection {
MAX, MIN, AVG, LENGTH, SUM, COUNT
}
public List listBuilders();
}
查询条件容器
import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import java.util.ArrayList;
import java.util.List;
public class ESQueryBuilderConstructor {
private int size = Integer.MAX_VALUE;
private int from = 0;
private String asc;
private String desc;
//查询条件容器
private List mustCriterions = new ArrayList<>();
private List shouldCriterions = new ArrayList<>();
private List mustNotCriterions = new ArrayList<>();
//构造builder
public QueryBuilder listBuilders() {
int count = mustCriterions.size() + shouldCriterions.size() + mustNotCriterions.size();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
QueryBuilder queryBuilder = null;
if (count >= 1) {
//must容器
if (!CollectionUtils.isEmpty(mustCriterions)) {
for (ESCriterion criterion : mustCriterions) {
for (QueryBuilder builder : criterion.listBuilders()) {
queryBuilder = boolQueryBuilder.must(builder);
}
}
}
//should容器
if (!CollectionUtils.isEmpty(shouldCriterions)) {
for (ESCriterion criterion : shouldCriterions) {
for (QueryBuilder builder : criterion.listBuilders()) {
queryBuilder = boolQueryBuilder.should(builder);
}
}
}
//must not 容器
if (!CollectionUtils.isEmpty(mustNotCriterions)) {
for (ESCriterion criterion : mustNotCriterions) {
for (QueryBuilder builder : criterion.listBuilders()) {
queryBuilder = boolQueryBuilder.mustNot(builder);
}
}
}
return queryBuilder;
} else {
return null;
}
}
/**
* 增加简单条件表达式
*/
public ESQueryBuilderConstructor must(ESCriterion criterion){
if(criterion!=null){
mustCriterions.add(criterion);
}
return this;
}
/**
* 增加简单条件表达式
*/
public ESQueryBuilderConstructor should(ESCriterion criterion){
if(criterion!=null){
shouldCriterions.add(criterion);