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

时间:2017-02-01 17:48:17

标签: 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上执行搜索,或从product_code中排除_all查询?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

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

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"
                    }
                }
            }]
        }
    }
}

希望这有帮助