如何在elasticsearch中使用带有索引的multi_match?

时间:2017-01-17 09:32:22

标签: elasticsearch elasticsearch-plugin

我有2个索引 USER 网址。我想根据索引在不同的字段上运行查询。

USER 索引中,查询应搜索名称 id 字段。 但在网址中,必须在标题 ID 字段上执行搜索。

POST /_search    
    {  
       "query":{  
          "indices":[  
             {  
                "indices":[  
                   "URL"
                ],
                "query":{  
                   "multi_match":{  
                      "query":"SMU ",
                      "fields":[  
                         "title",
                         "id"
                      ]
                   }
                }
             },
             {  
                "indices":[  
                   "USER"
                ],
                "query":{  
                   "multi_match":{  
                      "query":"SMU ",
                      "fields":[  
                         "name",
                         "id"
                      ]
                   }
                }
             }
          ]
       }
    }

以上查询无效。使其工作所需的变化是什么? 如何将multi_match搜索与索引搜索合并?

1 个答案:

答案 0 :(得分:3)

在ES 5中不推荐使用indices查询,但它仍然有效,你的结构只有一个糟糕的结构,即你需要将每个indices查询放在bool/filter子句中。

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "indices": {
            "indices": [
              "URL"
            ],
            "query": {
              "multi_match": {
                "query": "SMU ",
                "fields": [
                  "title",
                  "id"
                ]
              }
            }
          }
        },
        {
          "indices": {
            "indices": [
              "USER"
            ],
            "query": {
              "multi_match": {
                "query": "SMU ",
                "fields": [
                  "name",
                  "id"
                ]
              }
            }
          }
        }
      ]
    }
  }
}

由于不推荐使用indices查询,因此新的想法是在term字段上使用简单的_index查询。试试这个:

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": "URL"
                }
              },
              {
                "multi_match": {
                  "query": "SMU ",
                  "fields": [
                    "title",
                    "id"
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": "USER"
                }
              },
              {
                "multi_match": {
                  "query": "SMU ",
                  "fields": [
                    "name",
                    "id"
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}