ElasticSearch:ElasticSearch中的IN等效运算符

时间:2015-05-07 20:41:33

标签: elasticsearch

我试图在SQL中找到等同于IN \ NOT的ElasticSearch查询。

我知道我们可以使用带有多个OR的QueryString查询来获得相同的答案,但最终会有大量的OR。

有人可以分享这个例子吗?

3 个答案:

答案 0 :(得分:67)

类似于Chris建议的评论,IN的类似替代是terms filter(查询暗示得分,这可能会改善返回的订单)。

SELECT * FROM table WHERE id IN (1, 2, 3);

等效的Elasticsearch 1.x过滤器将是:

{
  "query" : {
    "filtered" : {
      "filter" : {
        "terms" : {
          "id" : [1, 2, 3]
        }
      }
    }
  }
}

等效的Elasticsearch 2.x +过滤器将是:

{
  "query" : {
    "bool" : {
      "filter" : {
        "terms" : {
          "id" : [1, 2, 3]
        }
      }
    }
  }
}

重要的一点是,terms过滤器(以及对此问题的查询)适用于完全匹配。隐含的是or操作,类似于IN

如果你想反转它,可以使用not过滤器,但我建议使用稍微冗长的bool / must_not过滤器(以养成使用{{1}的习惯} / boolmust)。

bool

总体而言,{ "query" : { "bool" : { "must_not" : { "terms" : { "id" : [1, 2, 3] } } } } } 复合查询语法为one of the most important filters in Elasticsearchbool(单数)和term过滤器(复数,如图所示)。

答案 1 :(得分:0)

1个条款

您可以在ElasticSearch中使用术语术语查询,该查询将充当IN

条款查询用于检查该值是否与 Array 中提供的任何值匹配。

2 不能

必须不可以在ElasticSearch中用作NOT。

例如。

GET my_index/my_type/_search
{
    "query" : {
         "bool" : {
              "must":[
                {
                   "terms": {
                        "id" : ["1234","12345","123456"]
                    }
                },
                {
                   "bool" : {
                        "must_not" : [
                            {
                              "match":{
                                  "id" : "123"
                               }
                            }
                        ]
                    }
                }
              ]
         }
    }
}
  1. 存在

如果有帮助,您还可以使用“存在” 查询来检查该字段是否存在。 例如 检查该字段是否存在

"exists" : {
      "field" : "mobileNumber"
   }

检查字段是否不存在

"bool":{
    "must_not" : [
        {
           "exists" : {
               "field" : "mobileNumber"
           }
        }
     ]
}

答案 2 :(得分:-1)

我看到了你的要求。 我编写了如下源代码。

我希望这可以帮助您解决问题。

sql查询:

Ñ

弹性搜索:

select * from tablename where fieldname in ('AA','BB');
相关问题