Home > Software design >  Elasticsearch wildcard search: when I add space to a query everything falls apart
Elasticsearch wildcard search: when I add space to a query everything falls apart

Time:12-02

I have a English dictionary Index, I search fields with the following JSON

GET /words/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "query_string": {
                  "default_field": "text",
                  "query": "*orhan*"
                }
              }
            ]
          }
        }
      ]
    }
  },
  "track_total_hits": true
}

My query purpose is to get all records if they include orhan name, and after running the query I get the results as expected;

_id _idex _score _type text
B6F1eoQBu3ncIuw4CyKL words 0.0 _doc orhan
cKN5eoQBu3ncIuw4JgxK words 0.0 _doc vorhand
drDzzYQBu3ncIuw4vn10 words 0.0 _doc orhan second word

I modify my query and I try the search orhan s but everything falls apart, the whole 54665 records were shown to me.

###
"bool": {
   "should": [
     {
         "query_string": {
         "default_field": "text",
         "query": "*orhan s*" // <- modified
      }
###

I can't add the whole response :) But I can provide, Response of total value:

"total": {
  "value": 54665,
  "relation": "eq"
},

My response shouldn't include the whole record just related records shown to me

Query: "query": "*orhan s*"

Response:

_id _idex _score _type text
drDzzYQBu3ncIuw4vn10 words 0.0 _doc orhan second word

CodePudding user response:

That's because the default operator is an OR, so you are catching all the words finishing with orhan OR starting with s.

You can change the operator:

GET /words/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "query_string": {
                  "default_field": "text",
                  "query": "*orhan s*",
                  "default_operator": "AND"
                }
              }
            ]
          }
        }
      ]
    }
  },
  "track_total_hits": true
}

Or add the operator to the query directly:

GET /test_words/_search
{
  "from": 0,
  "size": 10,
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "query_string": {
                  "default_field": "text",
                  "query": "*orhan AND s*"
                }
              }
            ]
          }
        }
      ]
    }
  },
  "track_total_hits": true
}
  • Related