基于elasticsearch7.9.3版本的操作
构建查询条件的基本代码
// 获取分页查询构造器
SearchSourceBuilder sourceBuilder = ElasticClientUtil.builderPageSearchBuilder(page, size);
// 构造父级查询条件
// 指定hasParent查询条件,限定查询结果的父文档类型是 店铺:goodsStore
QueryBuilder parentQueryBuilder;
// 商品店铺id不为空,根据id筛选,否则查询所有
if (StringUtils.hasLength(goodsStoreId)) {
parentQueryBuilder = new TermQueryBuilder(QueryFiledNameConstant.UNDERSCORE_ID, goodsStoreId);
}else {
parentQueryBuilder = new MatchAllQueryBuilder();
}
HasParentQueryBuilder hasParentQueryBuilder =
new HasParentQueryBuilder(GoodsRelationField.GOODS_STORE, parentQueryBuilder, false)
.innerHit(new InnerHitBuilder());
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().must(hasParentQueryBuilder);
// 构造子级查询条件
// 查询商品spu的子类型,商品sku信息,InnerHitBuilder默认size是3,因为商品spu下面的商品sku很可能不止3,所以设置一下size。
HasChildQueryBuilder hasChildQueryBuilder =
new HasChildQueryBuilder(GoodsRelationField.GOODS_SKU, QueryBuilders.matchAllQuery(), ScoreMode.None)
.innerHit(new InnerHitBuilder().setSize(GoodsRelationField.GOODS_SKU_MAX_SIZE));
boolQueryBuilder.must(hasChildQueryBuilder);
// 构造本级查询条件
// 商品名称是否为空
if (StringUtils.hasLength(goodsName)) {
boolQueryBuilder.must(QueryBuilders.wildcardQuery(QueryFiledNameConstant.GOODS_NAME,
StringPoolConstant.STAR + goodsName + StringPoolConstant.STAR));
}
sourceBuilder.query(boolQueryBuilder);
return sourceBuilder;
生成的对应的查询条件为
{
"query": {
"bool": {
"must": [
#本级查询条件 {
"ids": {
"values": [
"4"
],
"boost": 1.0
}
},
#父级查询条件
{
"has_parent": {
"query": {
"match_all": {
"boost": 1.0
}
},
"parent_type": "goodsStore",
"score": false,
"ignore_unmapped": false,
"boost": 1.0,
"inner_hits": {
"ignore_unmapped": false,
"from": 0,
"size": 3,
"version": false,
"seq_no_primary_term": false,
"explain": false,
"track_scores": false
}
}
},
#子级查询条件
{
"has_child": {
"query": {
"match_all": {
"boost": 1.0
}
},
"type": "goodsSku",
"score_mode": "none",
"min_children": 1,
"max_children": 2147483647,
"ignore_unmapped": false,
"boost": 1.0,
"inner_hits": {
"ignore_unmapped": false,
"from": 0,
"size": 20,
"version": false,
"seq_no_primary_term": false,
"explain": false,
"track_scores": false
}
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
}
|