搜索与嵌套数组Elasticsearch中的所有术语匹配的文档

时间:2018-02-05 13:56:26

标签: elasticsearch

我正在学习使用Elasticsearch作为基本的推荐引擎。 我的elasticsearch文档包含嵌套实体的记录,如下所示

PUT recs/user/1
{
  "name" : "Brad Pitt",
  "movies_liked": [
    {
      "name": "Forrest Gump",
      "score": 1
    },
    {
      "name": "Terminator",
      "score": 4
    },
    {
      "name": "Rambo",
      "score": 4
    },
    {
      "name": "Rocky",
      "score": 4
    },
    {
      "name": "Good Will Hunting",
      "score": 2
    }
  ]
}

PUT recs/user/2
{
  "name" : "Tom Cruise",
  "movies_liked": [
    {
      "name": "Forrest Gump",
      "score": 2
    },
    {
      "name": "Terminator",
      "score": 1
    },
    {
      "name": "Rocky IV",
      "score": 1
    },
    {
      "name": "Rocky",
      "score": 1
    },
    {
      "name": "Rocky II",
      "score": 1
    },
    {
      "name": "Predator",
      "score": 4
    }
  ]
}

我想搜索特别喜欢“Forrest Gump”,“Terminator”和“Rambo”的用户。

我使用了嵌套查询,目前看起来像这样

POST recs/user/_search
{
  "query": {
    "nested": {
      "path": "movies_liked",
      "query": {
        "terms": {
          "movies_liked.name": ["Forrest Gump","Terminator","Rambo"]

          }
        }

    }
  }
}

然而,当我执行此搜索时,我希望只看到第一条记录具有所有必需的条款,但在结果中我得到了两个记录。在第二个记录中,用户显然没有在他喜欢的列表中有“Rambo”。我知道这个查询正在对给定的术语执行“OR”操作,如何调整此查询以执行“AND”操作,以便只有具有所有术语的记录匹配?

1 个答案:

答案 0 :(得分:1)

  

如何调整此查询以执行" AND"操作,以便只有具有所有条款的记录匹配?

使用bool query

POST recs/user/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "movies_liked",
            "query": {
              "bool": {
                "must": [
                  {
                    "terms": {
                      "movies_liked.name": [
                        "Forrest Gump"
                      ]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "movies_liked",
            "query": {
              "bool": {
                "must": [
                  {
                    "terms": {
                      "movies_liked.name": [
                        "Terminator"
                      ]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "movies_liked",
            "query": {
              "bool": {
                "must": [
                  {
                    "terms": {
                      "movies_liked.name": [
                        "Rambo"
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

请注意,bool包含多个nested个查询,而不是相反。这很重要,因为nested查询的范围是嵌套文档,因为它基本上是hidden separate object

希望有所帮助!