Search code examples
elasticsearchelasticsearch-rails

Elastic Search Rails find partial record with id


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.


Solution

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