带有通配符和匹配条件的 Elasticsearch 查询

mic*_*ele 1 regex elasticsearch elasticsearch-query

我有这个索引:

    {
            "mappings": {
                "records" : {
                    "properties" : {
                        "suggest" : {
                            "type" : "completion",
                            "contexts": [
                                { 
                                    "name": "year",
                                    "type": "category",
                                    "path": "year"
                                }
                            ]
                        }
                    }
                }
            }
}
Run Code Online (Sandbox Code Playgroud)

我贴了一些记录:

POST http://localhost:9200/example/records
{
            "suggest": {
                "input": "foo123" ,
                "contexts": {
                    "year": "1999"
                }
            }
}

POST http://localhost:9200/example/records
{
            "suggest": {
                "input": "some123" ,
                "contexts": {
                    "year": "1999"
                }
            }
}
POST http://localhost:9200/example/records
{
            "suggest": {
                "input": "thing123" ,
                "contexts": {
                    "year": "2000"
                }
            }
}
Run Code Online (Sandbox Code Playgroud)

现在我会执行这个查询(类似sql):

SELECT * FROM example WHERE SUGGEST LIKE %123% AND YEAR=1999
Run Code Online (Sandbox Code Playgroud)

我可以在 Elastic Search 中做什么?

我输入:

    POST http://localhost:9200/example/records/_search?pretty
    {
    "query": {
        "bool": {
            "must": [
                   { "wildcard" : { "suggest" : "*123*" } }

            ], 
            "filter":[
                { "term" : { "year" : "1999" } }
                ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已返回此回复,但结果为空:

    {
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 0,
        "max_score": null,
        "hits": []
    }
}
Run Code Online (Sandbox Code Playgroud)

我期望返回此记录:

  • foo123,1999 年
  • 一些123,1999年

我能怎么做?

sla*_*wek 6

如果你关心分数,你需要使用bool 查询和 Must:

\n\n
{\n    "query": {\n        "bool": {\n            "must": [\n                { "wildcard" : { "name" : "*foo*" } },\n                { "term" : { "year" : "1999" } }\n            ]\n\xc2\xa0       }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者如果您只想过滤值并可能缓存过滤器,则使用过滤器:

\n\n
{\n    "query": {\n        "filter": {\n            "must": [\n                { "wildcard" : { "name" : "*foo*" } },\n                { "term" : { "year" : "1999" } }\n            ]\n\xc2\xa0       }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n