Search code examples
elasticsearch

Trouble escaping Elasticsearch query


In ES 5, say I want to search for "yabba/dabba". The docs mention escaping reserved characters by using a backslash. But if I do that, I get an error. Executing this query returns an error:

curl -XPOST "http://127.0.0.1:9200/messages/_search?pretty=true" --data-binary '{
  "query": {
    "bool": {
      "must": [
        {
       "bool" : {
        "should" : [
         {
          "query_string" : {
           "query" : "yabba\/dabba"
          }
         }
        ]
       }
      }
      ]
    }
  }
}'

The relevant part of the error returned is:

        "reason" : {
          "type" : "query_shard_exception",
          "reason" : "Failed to parse query [yabba/dabba]",
          "index_uuid" : "hhldqVnWSDelNyMdtiF0kw",
          "index" : "messages_201708291329",
          "caused_by" : {
            "type" : "parse_exception",
            "reason" : "Cannot parse 'yabba/dabba': Lexical error at line 1, column 12.  Encountered: <EOF> after : \"/dabba\"",
            "caused_by" : {
              "type" : "token_mgr_error",
              "reason" : "Lexical error at line 1, column 12.  Encountered: <EOF> after : \"/dabba\""
            }
          }

Solution

  • You also need to escape the backslash itself since it is located in a string. This will work:

    curl -XPOST "http://127.0.0.1:9200/messages/_search?pretty=true" --data-binary '{
      "query": {
        "bool": {
          "must": [
            {
           "bool" : {
            "should" : [
             {
              "query_string" : {
               "query" : "yabba\\/dabba"
              }
             }
            ]
           }
          }
          ]
        }
      }
    }'