我有一个非常简单的SQL查询:
SELECT * FROM table
WHERE
((sphereMin>=-17 AND sphereMax<=5) OR sphereMin<=-17)
AND
((sphereMax<=5 AND sphereMax>=-17) OR sphereMax>=5)
我必须使用高级API将该查询转换为ES。 这是相关代码:
SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = boolQuery();
BoolQueryBuilder booleanQuery1 = boolQuery();
BoolQueryBuilder subQuery1a = boolQuery();
booleanQuery1.must(subQuery1a);
RangeQueryBuilder subQuery1b = null;
subQuery1a.must(rangeQuery("sphereMin").gte(-17));
subQuery1a.must(rangeQuery("sphereMax").lte(5));
subQuery1b = rangeQuery("sphereMin").lte(-17);
booleanQuery1.should(subQuery1b);
BoolQueryBuilder booleanQuery2 = boolQuery();
BoolQueryBuilder subQuery2a = boolQuery();
booleanQuery2.must(subQuery2a);
RangeQueryBuilder subQuery2b = null;
subQuery2a.must(rangeQuery("sphereMax").gte(-17));
subQuery2a.must(rangeQuery("sphereMax").lte(5));
subQuery2b = rangeQuery("sphereMax").gte(5);
booleanQuery2.should(subQuery2b);
boolQueryBuilder.filter(booleanQuery1);
boolQueryBuilder.filter(booleanQuery2);
searchBuilder.query(boolQueryBuilder);
SearchRequest searchRequest = Requests.searchRequest(indexName).allowPartialSearchResults(true)
.source(searchBuilder).routing(routing);
从该代码创建的JSON是:
{
"bool" : {
"filter" : [
{
"bool" : {
"must" : [
{
"bool" : {
"must" : [
{
"range" : {
"sphereMin" : {
"from" : "-17",
"to" : null,
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
},
{
"range" : {
"sphereMax" : {
"from" : null,
"to" : "5",
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
],
"should" : [
{
"range" : {
"sphereMin" : {
"from" : null,
"to" : "-17",
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
},
{
"bool" : {
"must" : [
{
"bool" : {
"must" : [
{
"range" : {
"sphereMax" : {
"from" : "-17",
"to" : null,
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
},
{
"range" : {
"sphereMax" : {
"from" : null,
"to" : "5",
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
],
"should" : [
{
"range" : {
"sphereMax" : {
"from" : "5",
"to" : null,
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
在我看来不错,但该查询未返回与SQL查询相同的数据。 我在做什么错了?
答案 0 :(得分:0)
((sphereMax<=5 AND sphereMax>=-17) OR sphereMax>=-17)
ubQuery2a.must(rangeQuery("sphereMax").gte(-17));
subQuery2a.must(rangeQuery("sphereMax").lte(5));
subQuery2b = rangeQuery("sphereMax").gte(5);
5代替-17
;)
答案 1 :(得分:0)
以您的情况
booleanQuery1.must(subQuery1a);
应该是
booleanQuery1.should(subQuery1a);
以及
booleanQuery2.must(subQuery2a);
也应该
booleanQuery2.should(subQuery2a);
示例:
qb.should(a);
qb.should(b);
qb.should(c);
默认情况下,至少满足以下条件之一:a OR b OR c
而
qb.must(a);
qb.should(b);
表示必须 匹配,而b 应该。