【问题标题】:Elasticsearch partial matching of a number field数字字段的Elasticsearch部分匹配
【发布时间】:2017-06-02 13:00:19
【问题描述】:

我正在尝试部分匹配数字字段。在下面的查询中,我希望 id(定义为 long)匹配任何以 419 开头的文档。(所以 4191 应该匹配,419534 应该匹配,但不是 123419)

{
    "size": 20,
    "from": 0,
    "sort": [{
        "customerName": "asc"
    }],
    "query": {
        "bool": {
            "must": [{
                "bool": {
                    "should": [{
                        "term": {
                            "id": 419
                        }
                    }]
                }
            }]
        }
    }
}

有人在我的查询中使用了一个简洁的解决方案吗?

【问题讨论】:

  • 这个答案可能会有所帮助:stackoverflow.com/questions/36199531/… 但您可能需要将id 存储为字符串。
  • 将其转换为字符串很容易,但我希望有人知道更好/不同的解决方案。将数字分成几部分(例如 1 12 123)似乎也是搜索数字的一种复杂方式。我会努力将其转换为字符串,然后将其打开一段时间以查看是否有任何解决方案。再次感谢您的帮助,您太邪恶了。
  • 出乎意料,您能尝试使用query_string 并使用419* 作为查询吗?

标签: elasticsearch


【解决方案1】:

为避免出现 egde ngram,您可以在 id 映射中声明未分析的文本子字段:

"mappings": {
    "default": {
        "properties": {
            "id": {
                "type": "integer",
                "fields": {
                    "prefixed": {
                        "type":  "string",
                        "index":    "not_analyzed"
                    }
                }
            },
            ...
        }
    }
}

并对该字段使用prefix query

"query": {
    "prefix" : { 
        "id.prefixed" :  { "value" : 419 } 
    }
}

【讨论】:

  • 这确实是我最终要做的,这似乎是目前实现这一目标的唯一方法。我会接受答案,因为它与 Val 提供的解决方案和我最初想到的解决方案相同。如果有更好的答案,我会接受。
【解决方案2】:

在字符串字段中可以使用通配符查询:

{
"query" : {
    "wildcard" : { "id" : "*419*" }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多