0

I'm trying to implement an auto complete using Rails and Elastic Search using the elasticsearch-rails gem.

Say I have the following records:

[{id: 1, name: "John White"}, 
 {id:2, name: "Betty Johnson"}]

Which elastic search method could I use to return both records upon searching "John".

The autocomplete would only return "John White" and it does so without returning id:1.

jdkealy
  • 4,807
  • 6
  • 34
  • 56

1 Answers1

2

One of way would be using edgeNgram filter:

PUT office
{
  "settings": {
    "analysis": {
      "analyzer": {
        "default_index":{
          "type":"custom",
          "tokenizer":"standard",
          "filter":["lowercase","edgeNgram_"]
        }
      },
      "filter": {
        "edgeNgram_":{
          "type":"edgeNgram",
          "min_gram":"2",
          "max_gram":"10"
        }
      }
    }
  },
  "mappings": {
    "employee":{
      "properties": {
        "name":{
          "type": "string"
        }
      }
    }
  }
}

PUT office/employee/1
{
  "name": "John White"
}
PUT office/employee/2
{
  "name": "Betty Johnson"
}
GET office/employee/_search
{
  "query": {
    "match": {
      "name": "John"
    }
  }
}

And the result would be:

{
   "took": 5,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0.19178301,
      "hits": [
         {
            "_index": "office",
            "_type": "employee",
            "_id": "1",
            "_score": 0.19178301,
            "_source": {
               "name": "John White"
            }
         },
         {
            "_index": "office",
            "_type": "employee",
            "_id": "2",
            "_score": 0.19178301,
            "_source": {
               "name": "Betty Johnson"
            }
         }
      ]
   }
}
monu
  • 698
  • 4
  • 10
  • Thanks a bunch! I got this working I think on my end. The only problem is what if you search "John Black". Why would it return results ? Any way to exclude non-matches like that? – jdkealy Jun 29 '15 at 21:10