Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using wildcards in phrases with Elasticsearch Query String Query

Using the wildcard operator, I can match terms starting with some value:

{
    "query": {
        "query_string" : {
            "query" : "subject:cell*"
        }
    }
}

The subject field here is a keyword field (non-analyzed). This works fine, but I cannot figure out how to find terms starting with, say, "cellular contr". Trying double quotes did not yield the expected results:

{
    "query": {
        "query_string" : {
            "query" : "subject:\"cellular contr*\""
        }
    }
}

Note: phrase search works fine with exact matches, just not with the wildcard. My guess is that the star is not interpreted as a wildcard operator inside the double quotes. Is that correct? And is there any other way to use the wildcard operator with a phrase?

Note: I have to use Query String Query, since the query is coming from user input.

(I know I could resort to regexp, but would prefer not to)

like image 264
danmichaelo Avatar asked Mar 05 '17 21:03

danmichaelo


2 Answers

In addition to the custom analyzer as pointed by Hemed, you need to do search as below -

{
    "query": {
        "query_string" : {
            "query" : "subject:cellular\\ contr*"
        }
    }
}

Found it after a lot of research and tries!

like image 132
HM14 Avatar answered Sep 23 '22 09:09

HM14


EDIT: Define custom analyzer for searching:-

settings:
   index:
     analysis:
       analyzer:
         keyword_analyzer:
           type: custom
           tokenizer: keyword
           filter:
             - lowercase

Found out that you need to use Prefix Query in this case, because Query String Query always segments on spaces during parsing.

But since you are using lowecase filter in this field and Prefix Query does not support analyzer, you would have to lowercase user input before appending it to the query.

New query becomes:-

   {
        "query": {
            "prefix" : {
                "subject" : "cellular contr"
            }
        }
    }

Alternatively, you can use Match Phrase Query which supports analyzer.

{
    "query": {
        "match_phrase_prefix" : {
            "subject" : {
                 "query" : "Cellular contr",
                  "analyzer" : "keyword_analyzer",
                  "max_expansions" : 100
                 }
              }
         }
    }
like image 41
Hemed Avatar answered Sep 22 '22 09:09

Hemed