Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

Elasticsearch get results character by character

Maybe I am not reading the documentation for elastic search correctly, but I am confused on how to get all indexes like {"name": "s"} to pull all the name data that has an "s" in it.

Then when the user types more letters it keeps filtering down, standard way to seach, similar to google.

I have tried

curl -XGET "http://localhost:9200/schools/_search" -d "{""query"": { ""match"": {""name"": {""query"": ""s""} } }}"

Also along my hacking away for a solution I have tried using fuzzy searching and other things that didnt work so well.

I am asking how can I get all records by "s" then filter it down for the next letter in the sequence i.e adding "st" then filtering more when adding "stanf" etc?

Upvotes: 0

Views: 142

Answers (1)

whythecode
whythecode

Reputation: 1107

I think you're looking for this: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters-completion.html

You need to:

  • Index the field (or a subfield of it) as "type": "completion"

  • Do a _suggest query

Following are some partially modified code bits from the Elasticsearch documentation.

Schema:

  curl -X PUT localhost:9200/music
  curl -X PUT localhost:9200/music/song/_mapping -d '{
    "song" : {
          "properties" : {
              "name" : { "type" : "string" },
              "suggest" : { "type" : "completion",
                            "index_analyzer" : "simple",
                            "search_analyzer" : "simple",
                            "payloads" : true
              }
          }
      }
  }'

Document:

curl -X PUT 'localhost:9200/music/song/1?refresh=true' -d '{
    "name" : "Firstname Lastname",
    "suggest" : [ "Firstname Lastname", 
                  "Lastname, Firstname" ]
}'

Query:

curl -X POST 'localhost:9200/music/_suggest?pretty' -d '{
    "suggestionqueryname": {
        "completion": {
            "field": "suggest"
        },
        "text": "fir"
    }
}'

Upvotes: 1

Related Questions