弹性搜索查询以查找嵌套字段“包含”X对象的文档

时间:2018-02-22 17:30:19

标签: database elasticsearch

这是我的数据对于名为 video_service_inventory 的弹性搜索索引的示例:

{
    'video_service': 'netflix',
    'movies' : [
        {'title': 'Mission Impossible', 'genre: 'action'},
        {'title': 'The Hangover', 'genre': 'comedy'},
        {'title': 'Zoolander', 'genre': 'comedy'},
        {'title': 'The Ring', 'genre': 'horror'}
    ]
}

我已在索引中确定“电影”字段的类型为“嵌套”

我想写一个查询,说“让我所有包含这两部电影的video_services”

{'title': 'Mission Impossible', 'genre: 'action'}
AND
{'title': 'The Ring', 'genre': 'horror'}

其中,标题和流派必须匹配。如果存在一部电影而不存在另一部电影,我不希望该查询返回该视频服务。

理想情况下,我想在1个查询中执行此操作。到目前为止,我还没有找到解决方案。

有人建议您撰写此搜索查询吗?

1 个答案:

答案 0 :(得分:0)

语法可能因弹性搜索版本而异,但通常您应该在bool中组合多个嵌套查询 - 必须查询。对于嵌套查询,您需要指定“导航”到嵌套文档的路径,并且需要使用部件+字段名称限定属性:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "movies",
            "query": {
              "bool": {
                "must": [
                  { "terms": { "movies.title": "Mission Impossible" } },
                  { "terms": { "movies.genre": "action" } }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "movies",
            "query": {
              "bool": {
                "must": [
                  { "terms": { "movies.title": "The Ring" } },
                  { "terms": { "movies.genre": "horror" } }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

此示例假定标题和流派字段不是分析属性。在较新版本的elasticsearch中,您可能会将它们视为.keyword字段,然后您可以使用“movies.genre.keyword”查询未分析的数据版本。

有关bool查询的详细信息,您可以查看ES网站上的文档: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

对于嵌套查询: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html