ElasticSearch(十二) Bool Query JAVA API
Bool Query 用于组合多个叶子或复合查询子句的默认查询
must 相当于 与 & =
must not 相当于 非 ~ !=
should 相当于 或 | or
filter 过滤
boolQuery() .must(termQuery("content", "test1"))
.must(termQuery("content", "test4"))
.mustNot(termQuery("content", "test2"))
.should(termQuery("content", "test3"))
.filter(termQuery("content", "test5"));
private SearchRequest getSearchRequest(RequestType request) {
SearchRequest sr = new SearchRequest();
//指定索引名称,如未指定则会查询所有
sr.indices(ElasticSearchConst.XXX_INDEX);
sr.types(ElasticSearchConst.XXX_TYPE);
SearchSourceBuilder source = new SearchSourceBuilder();
BoolQueryBuilder bq = QueryBuilders.boolQuery();
getQueryBuilder(request, bq);
// from 从0开始,包含前后边界 实际是 <= >=
source.from(request.getRowStart());
source.size(request.getRowSize());
source.query(bq);
setSort(request, source);
sr.source(source);
return sr;
}
private void getQueryBuilder(RequestType request, BoolQueryBuilder bq) {
getOrderQueryBuilder(request, bq);
addPurchaseOrderQueryBuilder(request, bq);
}
/**
* 查询条件
*
* @param request
* @param bq
*/
private void getOrderQueryBuilder(RequestType request, BoolQueryBuilder bq) {
// termQuery 精确匹配,不分词 相当于 等于 =
//Type.childType 多层类型嵌套,具体索引结构,参考mapping
// GET yourindexname/_mapping
Mapping:
{
"yourindexname": {
"mappings": {
"type1": {
"properties": {
"childtype": {
"properties": {
"cedStatus": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
bq.must(QueryBuilders.termQuery("Type.childType", request.getOrderId()));
//rangeQuery 范围查询,最大范围不超过1w
bq.must(QueryBuilders.rangeQuery("Type.childType.departureDate")
.gte(DateUtil.toSqlTimeStamp(request.getDepartureDateStart().getTime()).getTime())
.lte(DateUtil.toSqlTimeStamp(request.getDepartureDateEnd().getTime()).getTime()));
//QueryBuilders.matchPhraseQuery 匹配查询,不分词,相当于 contains
//matchPhraseQuery 是直接以一个短语的形式查询,顺序无差,且连接在一起
pobq.must(QueryBuilders.matchPhraseQuery(
String.format("%s%s%s", preFix, i, ".vacationVBKPurchaseOrderBaseInfoDto.contactName"),
request.getContactName()));