Elasticsearch 匹配多个字段

5 投票
3 回答
12089 浏览
提问于 2025-04-18 01:41

我最近在一个网站上使用 elasticsearch。我的场景是,我需要在一个 field 中搜索一个字符串。如果这个 field 叫做 title,那么我的搜索查询是:

"query" :{"match": {"title": my_query_string}}.

但是现在我需要在里面添加另一个 field,比如说 category。所以我需要找到那些在 categorysome_categorytitlemy_query_string 的匹配项。我试过用 multi_match,但没有得到我想要的结果。现在我在研究 query filter。但是有没有办法在我的 match 查询中添加这两个字段的条件呢?

3 个回答

0
      "query": {
            "filtered": {
                "query": {
                    "bool": {
                        "should": [
                            {"match": {"title": "bold title"},
                            {"match": {"body": "nice body"}}
                        ]
                    }
                },
                "filter": {
                    "term": {
                        "category": "xxx"
                    }
                }
            }
        }

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

3

好的,我觉得你需要的是这样的东西:

"query": {
    "filtered": {
        "query": {
            "match": {
                "title": YOUR_QUERY_STRING,
            }
        },
        "filter": {
            "term": {
                "category": YOUR_CATEGORY
            }
        }
    }
}

如果你的 category 字段是经过分析的,那么在过滤的时候你需要用 match 而不是 term

10
GET indice/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "title": "title"
          }
        },
        {
          "match": {
            "category": "category"
          }
        }
      ]
    }
  }
}

如果需要的话,可以把 should 替换成 must

撰写回答