michele
michele

Reputation: 26598

Elasticsearch query with wildcard and match conditions

I have this index:

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

I put some records:

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

Now I would do this query (sql like):

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

How can I do in Elastic Search?

I type:

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

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

I have returned this response with blank results:

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

I am expecting to have returned this records:

How can I do?

Upvotes: 1

Views: 8527

Answers (1)

slawek
slawek

Reputation: 2779

You need to use bool query with must if you care about score:

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

or with filter if you just want to filter values and possibly cache the filter:

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

Upvotes: 6

Related Questions