我正在寻找 Elasticsearch 等效的 SQL In 查询,如下所示
SELECT * from table
WHERE (section , class) in (('a','1'), ('b', '2'))
我知道如何在elasticsearch中使用In query来查询单个字段
SELECT * FROM table WHERE class IN ('1', '2');
Elasticsearch 查询 -
{
"query" : {
"bool" : {
"filter" : {
"terms" : {
"class" : ['1', '2']
}
}
}
}
}
我的实际问题陈述 -
索引数据示例:
[
{
"_index" : "some_index",
"_type" : "_doc",
"_id" : "41",
"_score" : 1.0,
"_source" : {
"class" : "1",
"section" : "a",
"attribute_3" : "hello world"
},
{
"_index" : "some_index",
"_type" : "_doc",
"_id" : "42",
"_score" : 1.0,
"_source" : {
"class" : "2",
"section" : "a",
"attribute_3" : "hello world"
},
{
"_index" : "some_index",
"_type" : "_doc",
"_id" : "43",
"_score" : 1.0,
"_source" : {
"class" : "1",
"section" : "b",
"attribute_3" : "hello world"
},
{
"_index" : "some_index",
"_type" : "_doc",
"_id" : "44",
"_score" : 1.0,
"_source" : {
"class" : "2",
"section" : "b",
"attribute_3" : "hello world"
},
{
"_index" : "some_index",
"_type" : "_doc",
"_id" : "45",
"_score" : 1.0,
"_source" : {
"class" : "3",
"section" : "b",
"attribute_3" : "hello world"
}
]
我想对数据使用过滤器,其中(类为 1 AND 部分为 a)OR(类为 2 AND 部分为 b) 注意:我正在动态准备这个“OR”组合,并且它将是两个以上的组合。
我预期的搜索结果应该是 -
[{
"_index" : "some_index",
"_type" : "_doc",
"_id" : "41",
"_score" : 1.0,
"_source" : {
"class" : "1",
"section" : "a",
"attribute_3" : "hello world"
},
{
"_index" : "some_index",
"_type" : "_doc",
"_id" : "44",
"_score" : 1.0,
"_source" : {
"class" : "2",
"section" : "b",
"attribute_3" : "hello world"
}]
最佳答案
这将转化为:
{
"query": {
"bool": {
"should": [
{
"bool": {
"must": [
{
"term": {
"a": 0
}
},
{
"term": {
"b": 9
}
}
]
}
},
{
"bool": {
"must": [
{
"term": {
"a": 0
}
},
{
"term": {
"b": 4
}
}
]
}
}
]
}
}
}
但如果 a
始终为 0
,如您在示例中提到的,则查询可以改写为:
{
"query": {
"bool": {
"must": [
{
"term": {
"a": 0
}
},
{
"terms": {
"b": [
9,
4
]
}
}
]
}
}
}
关于Elasticsearch 相当于具有多个字段的 SQL In Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64906999/