如何在弹性搜索中搜索 "foo ba*"?

How to search for "foo ba*" in elastic search?

Elasticsearch 中有 match_phrase 个查询,还有 wildcard 个查询。有没有办法将两者结合起来搜索类似“foo ba*”的内容?

这个问题的答案在于使用“跨度查询”。如官方文档所述:

Span queries are low-level positional queries which provide expert control over the order and proximity of the specified terms.

最终查询将如下所示:

{
    "query": {
        "span_near" : {
            "clauses" : [
                { "span_term" : { "field" : "foo" } },
                { "span_multi" : { "match": { "wildcard": { "field" : "ba*" } } } }
            ],
            "slop" : 0,
            "in_order" : true
        }
    }
}

注意:

  1. slop用来表示不同的“跨度项”可以达到多远。这里因为我们希望它们彼此相邻,所以我们指定 slop 为 0.
  2. in_order 是为了判断词条的顺序是否重要。在我们的例子中,它是 - 因此 true.