首页 > 解决方案 > 在 Elasticsearch 中实现基于限制的查询

问题描述

我正在尝试在 ElasticSearch (Nest) 中实现一个查询,其中只返回满足某些限制的文档。每个文档都有一个字符串数组(限制),查询也将得到一个字符串数组(我们称之为“satisfiedRestrictions”),目标是仅检索(过滤掉)那些仅具有指定限制的文档在“满足限制”中

假设我有文件

[
 {
  "Id":1,
  "Restrictions":["restriction1", "restriction2"]
 },
 {
  "Id":2,
  "Restrictions":["restriction1"]
 },
 {
  "Id":3,
  "Restrictions":["restriction1", "restriction2", "restriction3"]
 }
]

鉴于satisfiedRestrictions = ["restriction1", "restriction2"]查询应返回 ID 为 1 和 2 的文档。文档 3 具有未在satisfiedRestrictions参数中指定的额外限制(“restriction3”),因此应将其从结果中排除。

可以用must_not子句解决这个问题(不能匹配“restriction3”),但这会假设所有可能的限制值都应该保存在某个地方。理想的解决方案是不必这样做。

有没有实现这一目标的好方法,或者这种“基于限制”的模型是否无法解决?

标签: elasticsearch

解决方案


好吧,如果您的数组中有不同的值,这应该可以工作:

{
  "query": {
    "bool" : {
      "must" : {
        "terms" : { "Restrictions" : ["restriction1", "restriction2"] }
      },
      "must" : {
        "script" : {
          "script" : {
            "inline" : "doc[\"Restrictions\"].length < 3",
          }
        }
      }
    }
  }
}

编辑:== 2 替换为 < 3


推荐阅读