小编典典

在Elasticsearch中使用“ AND”运算符使用数组进行多字段搜索

elasticsearch

我想以查询其他字段的相同方式将多值字段的值查询为单独的“字段”。我有这样的数据结构:

{
  name: 'foo one',
  alternate_name: 'bar two',
  lay_name: 'baz three',
  tags: ['stuff like', 'this that']
}

我的查询如下所示:

{
  query:
    query: stuff
    type: 'best_fields',
    fields: ['name', 'alternate_name', 'lay_name', 'tags'],
    operator: 'and'
}

仅当值包含我的整个查询时,“类型”和“运算符”才能完美匹配单个值字段。例如,查询“ foo two”不会返回匹配项。

我希望标签字段的行为相同。现在,查询“东西”将在不应该返回匹配项时返回匹配项,因为没有字段或标记值将两个单词都包含在一个值中。有没有办法做到这一点?

编辑 Val的评估当场。我已经将映射更新为以下内容(使用elasticsearch-
rails
/ elasticsearch-
model
):

mapping dynamic: false, include_in_all: true do
  ... other fields ...
  indexes :tags, type: 'nested' do
    indexes :tag, type: 'string', include_in_parent: true
  end
end

阅读 542

收藏
2020-06-22

共1个答案

小编典典

请显示您的映射类型,但是我怀疑您的tags字段是一个简单的string字段,如下所示:

{
    "your_type" : {
        "properties" : {
            "tags" : {
                "type" : "string"
            }
        }
    }
}

在这种情况下,ES会tags在索引编制时将字段中的所有标签“扁平化” ,如下所示:

tags: "stuff", "like", "this", "that"

即,这就是为什么在查询“东西”时得到结果的原因,因为该tags字段包含两个单词。

前进的方法是制作tags一个嵌套的对象类型,像这样

{
    "your_type" : {
        "properties" : {
            "tags" : {
                "type" : "nested",
                "properties": {
                    "tag" : {"type": "string" }
                }
            }
        }
    }
}

您需要重新索引数据,但至少查询tags: "stuff that"将不再返回任何内容。您的标记令牌将按照您的期望“保持在一起”。试试看。

2020-06-22