Jimmy
Jimmy

Reputation: 12487

Elasticsearch - Not require an exact match

Currently I have an item in my elasticsearch index with the title: testing123.

When I search for it, I can only get it returned if I search testing123 exactly. However, I want to be able to search testing and have it returned too.

How can I have it so the search must start with that term but also not be an exact match?

Upvotes: 2

Views: 2193

Answers (2)

Dan Tuffery
Dan Tuffery

Reputation: 5924

Use the Simple Analyzer in your mapping.

Create an index where the title field is indexed using the both the standard (default) and simple analyzers:

POST /demo
{
    "mappings": {
        "doc": {
            "properties": {
                "title": {
                    "type": "string",
                    "fields": {
                        "simple": {
                            "type": "string",
                            "analyzer": "simple"
                        }
                    }
                }
            }
        }
    }
}

Index a document

POST /demo/doc/1
{
    "title": "testing123"
}

Finally, search using the multi_match query:

POST /demo/doc/_search
{
    "query": {
        "multi_match": {
            "fields": [
                "title",
                "title.simple"
            ],
            "query": "testing"
        }
    }
}

This query returns the document. If you were to change the query term to testing123 there would also be a match.

Another possible solution would be to use the Prefix Query.

Upvotes: 1

Paradise
Paradise

Reputation: 1468

I believe that you're looking for wildcards.

Matches documents that have fields matching a wildcard expression. Supported wildcards are *, which matches any character sequence (including the empty one), and ?, which matches any single character.

Wildcards are basically a "match anything here". So your search would look like

testing*

which would match

testing

testing123

testingthings

but would not match

test123ing

or

test

Upvotes: 1

Related Questions