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

时间:2018-02-27 13:52:05

标签: regex elasticsearch elasticsearch-query

我有这个索引:

    {
            "mappings": {
                "records" : {
                    "properties" : {
                        "suggest" : {
                            "type" : "completion",
                            "contexts": [
                                { 
                                    "name": "year",
                                    "type": "category",
                                    "path": "year"
                                }
                            ]
                        }
                    }
                }
            }
}

我写了一些记录:

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

现在我会做这个查询(像sql一样):

SELECT * FROM example WHERE SUGGEST LIKE %123% AND YEAR=1999

如何在弹性搜索中进行操作?

我输入:

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

            ], 
            "filter":[
                { "term" : { "year" : "1999" } }
                ]
        }
    }
}

我已将此回复与空白结果一起返回:

    {
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 0,
        "max_score": null,
        "hits": []
    }
}

我希望能够归还这些记录:

  • foo123,1999年
  • some123,1999;

我该怎么办?

1 个答案:

答案 0 :(得分:0)

如果你关心得分,你需要使用必须bool query

{
    "query": {
        "bool": {
            "must": [
                { "wildcard" : { "name" : "*foo*" } },
                { "term" : { "year" : "1999" } }
            ]
        }
    }
}

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

{
    "query": {
        "filter": {
            "must": [
                { "wildcard" : { "name" : "*foo*" } },
                { "term" : { "year" : "1999" } }
            ]
        }
    }
}