在 ElasticSearch 中有条件地添加模糊性



我的所有文档中都有十个左右的字段:特别是product_code,每个文档都是唯一的,类型为字符串。

我有一个关于_all的匹配查询,效果很好,但我想执行"模糊匹配",同时保留搜索精确product_code的能力

这是我尝试过的:

"query": {
    "bool": {
        "should": [
            {
                "match": {
                    "product_code": {
                        "query": searchString,
                        "operator": "AND"
                    }
                }
            },
            {
                "match": {
                    "_all": {
                        "query": searchString,
                        "operator": "AND"
                        "fuzziness": 2,
                        "prefix_length": 2
                    }
                }
            }
        ]
    }
}

这种方法的问题在于模糊性也应用于搜索product_code,因为它包含在_all中。

有没有办法先对product_code执行搜索,如果未找到结果,则对_all执行搜索,或从_all查询中排除product_code

任何帮助将不胜感激。

是的,您可以使用以下映射将product_code从_all中排除。

PUT index_name
{
    "settings": {
        "analysis": {
            "analyzer": {},
            "filter": {}
        }
    },
    "mappings": {
        "type_name": {
            "properties": {
                "product_code": {
                    "type": "string",
                    "include_in_all": false
                }
            }
        }
    }
}

或者,您可以使用query_string搜索,这也提供模糊性。

使用以下查询,该查询使用具有 AND 运算符和模糊性设置的查询字符串

{
    "query": {
        "bool": {
            "should": [{
                "query_string": {
                    "fields": ["product_code", "other_field"],
                    "query": "this is my string",
                    "default_operator": "AND",
                    "fuzziness": 2,
                    "fuzzy_prefix_length": 2
                }
            }, {
                "match": {
                    "product_code": {
                        "query": "this is my string",
                        "operator": "AND"
                    }
                }
            }]
        }
    }
}

希望这有帮助

最新更新