Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escaping forward slashes in elasticsearch

I am doing a general search against elasticsearch (1.7) and all is well except my account numbers have forward slashes in them. The account number field is not the id field and is "not_analyzed".

If I do a search on an account number e.g. AC/1234/A01 then I get thousands of results, presumably because it is doing a regex search (?).

{
   "query" : { "query_string" : {"query" : "AC/1234/A01"} }
}

I can get the result I want by doing an exact match search

  {
    "query" : { "query_string" : {"query" : "\"AC/1234/A01\""} }
  }

This actually gives me the result I want and probably will fit the bill as a backup option (surrounding all 'single word' searches with quotes). However I'm thinking if they do a multiple word search including the account number I will be back to thousands of results and although I can't see the value of that search I would like to avoid it happening.

Essentially I have a java app querying elastic search and I would like to escape all forward slashes entered in the GUI.

My Googling has told me that

{
  "query" : { "query_string" : {"query" : "AC\\/1234\\/A01"} }
}

ought to do this but it makes no difference, the query works but I still get thousands of results.

Could anyone point me in the right direction ?

like image 855
gringogordo Avatar asked Aug 12 '15 11:08

gringogordo


2 Answers

You should get what you want without escaping anything simply by specifying a keyword analyzer for the query string, like this:

{
  "query" : { 
     "query_string" : {
        "query" : "AC\\/1234\\/A01",
        "analyzer": "keyword"         <---- add this line
     } 
  }
}

If you don't do this, the standard analyzer is used (and will tokenize your query string) whatever the type of your field is or whether it is not_analyzed or not.

like image 161
Val Avatar answered Sep 28 '22 11:09

Val


Use this query as example:

{
  "query": {
    "query_string": {
      "fields": [
        "account_number.keyword"
      ],
      "query": "AC\\/1234\\/A01",
      "analyzer": "keyword"
    }
  }
}
like image 31
Thiago Falcao Avatar answered Sep 28 '22 10:09

Thiago Falcao