ElasticSearch - prefix with space and filter

My ElasticSearch server contains documents of the following form:

{
    "_index": "xindex",
    "_type": "xtype",
    "_id": "1100",
    "_score": 3.00010,
    "_source": {
        "_id": "2333345",
        "field1": "11111111111111",
        "field2": "y",
        "name": "hello world",
    }
}

      

I need to get all documents with the name prefix "hello wo" and field2 "y". Tried many queries and none worked. There are all sorts of solutions to prefix with space issue, but when adding filtering / other query for field2, the results get corrupted.

Thank.

+3


source to share


1 answer


This can be done in 3 steps:

  • Change your mapping of the name field to not_analyzed
  • Use the match_phrase_prefix request (documentation here )
  • Filter the results of this query by enclosing it in the filtered query and using the term filter on field2 with the value "y"

You can see how it works with the following dataset:

PUT test/prefix/_mapping
{
  "properties": {
    "name":{
      "type": "string",
      "index": "not_analyzed"
    }
  }
}

//should match
PUT test/prefix/2333345
{
  "field1": "11111111111111",
  "field2": "y",
  "name": "hello world"
}

//should match    
PUT test/prefix/1112223
{
  "field1": "22222222222222",
  "field2": "y",
  "name": "hello wombat"
}

//should not match (field2 value is different)
PUT test/prefix/4445556
{
  "field1": "33333333333333",
  "field2": "z",
  "name": "hello world"
}

//should not match (second word not starting with wo)
PUT test/prefix/4445556
{
  "field1": "33333333333333",
  "field2": "y",
  "name": "hello zombie"
}

      



Then the request:

GET test/prefix/_search
{
  "query": {
    "filtered": {
      "query": {
        "match_phrase_prefix" : {
        "name" : "hello wo"
        }
      },
      "filter": {
        "term": {
          "field2": "y"
        }  
      }
    } 
  }
}

      

which outputs docs 1112223 and 2333345 as expected:

{
   "took": 20,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 1.592944,
      "hits": [
         {
            "_index": "test",
            "_type": "prefix",
            "_id": "2333345",
            "_score": 1.592944,
            "_source": {
               "field1": "11111111111111",
               "field2": "y",
               "name": "hello world"
            }
         },
         {
            "_index": "test",
            "_type": "prefix",
            "_id": "1112223",
            "_score": 1.592944,
            "_source": {
               "field1": "22222222222222",
               "field2": "y",
               "name": "hello wombat"
            }
         }
      ]
   }
}

      

+3


source







All Articles