Search code examples
opensearchamazon-opensearch

Cannot find # in OpenSearch query


I have an index that includes a field and when a '#' is input, I cannot get the query to find the #.

Field Data: "#3213939"

Query:

GET /invoices/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "referenceNumber": {
              "query": "#32"
            }
          }
        },
        {
          "wildcard": {
            "referenceNumber": {
              "value": "*#32*"
            }
          }
        }
      ]
    }
  }
}

Solution

  • "#" character drops during standard text analyzer this is why you can't find it.

    POST _analyze
    {
      "text": ["#3213939"]
    }
    

    Response:

    {
      "tokens": [
        {
          "token": "3213939",
          "start_offset": 1,
          "end_offset": 8,
          "type": "<NUM>",
          "position": 0
        }
      ]
    }
    

    You can update the analyzer and customize it. https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-standard-analyzer.html

    OR

    you can use referenceNumber.keyword field.

    GET test_invoices/_search
    {
      "query": {
        "bool": {
          "should": [
            
            {
              "match": {
                "referenceNumber": {
                  "query": "#32"
                }
              }
            },
            {
              "wildcard": {
                "referenceNumber.keyword": {
                  "value": "*#32*"
                }
              }
            }
          ]
        }
      }
    }