首页 > 解决方案 > 如何在 Elasticsearch 中使用 multi_match 查询传递多个值以在多个记录中搜索多个字段

问题描述

{
 "query": {
  "bool": {
    "must": {
      "bool": {
        "must": [
          {
            "multi_match": {
              "query": [
                "869336","45345345"
              ],
              "type": "phrase_prefix",
              "fields": [
                "id",
                "accountNo",
                "moblileNo"
              ]
            }
          }
        ],
        "should": [],
        "must_not": []
      }
    },
    "filter": {
      "bool": {
        "must": {
          "bool": {
            "must": [],
            "should": [],
            "must_not": []
          }
        }
      }
    }
  }
}

}

只需要使用多重匹配查询。我在查询中提到了一些示例字段。当我在邮递员上运行它时出现以下错误:[查询]之后的[multi_match]未知令牌[START_ARRAY]

标签: node.jselasticsearchgraphql

解决方案


对于错误,因为query只需要一个输入字符串。

它可以有多个值,例如"query" : "869336 45345345"用空格分隔的值。这是如何工作的,您可能可以通过此链接

现在研究您的场景,假设您希望对ie和的值都应用短语匹配查询,您只需要在其单独的多匹配查询中分离出这些值。86933645345345

POST <your_index_name>/_search
{
  "query": {
    "bool": {
      "must": {
        "bool": {
          "must": [
            {
              "multi_match": {
                "query": "869336",
                "type": "phrase_prefix",
                "fields": [
                  "accountNo",
                  "moblileNo"
                ]
              }
            },
            {
              "multi_match": {
                "query": "45345345",
                "type": "phrase_prefix",
                "fields": [
                  "accountNo",
                  "moblileNo"
                ]
              }
            }
          ],
          "should": [],
          "must_not": []
        }
      },
      "filter": {
        "bool": {
          "must": {
            "bool": {
              "must": [],
              "should": [],
              "must_not": []
            }
          }
        }
      }
    }
  }
}

现在,如果您不想应用phrase_prefix,而是想返回在任何字段中具有两个值的所有文档,您可以简单地编写如下查询:

POST my-multimatch-index/_search
{
  "query": {
    "bool": {
      "must": {
        "bool": {
          "must": [
            {
              "multi_match": {
                "query": "869336 45345345",
                "fields": [
                  "accountNo",
                  "moblileNo"
                ],
                "type": "cross_fields",              <--- Note this
                "operator": "and"                    <--- This would mean only return those documents having both these value. 
              } 
            }
          ],
          "should": [],
          "must_not": []
        }
      },
      "filter": {
        "bool": {
          "must": {
            "bool": {
              "must": [],
              "should": [],
              "must_not": []
            }
          }
        }
      }
    }
  }
}

请注意上述评论以及我如何使用cross-fields。最好通过链接获得更好的理解。

无论如何,请随时提出问题,我希望这会有所帮助!


推荐阅读