Home > Software engineering >  Elastic search match query with pattern
Elastic search match query with pattern

Time:09-30

I have a column where all the values start with "ARK". For example

number
ARK101223
ARK123422
ARK234002
ARK234177

I need to get all the records for the column number that matches with ARK using elastic search. Whereever I have the number as column and matches with ARK, I need to retrieve those records only. Some records will not have number as column so I want those to be ignored..

Below is the query that I tried but not working

{
  "query": {
    "bool": {
      "must": [
        {
          "prefix": {
            "number.keyword": "ARK"
          }
        },
        {
          "range": {
            "date_1": {
              "gte": "2022-01-01 01:00:00",
              "lte": "2022-03-10 01:00:00"
            }
          },
          "sort": [
            {
              "date_1": {
                "order": "asc"
              },
              "date_2": {
                "order": "asc"
              },
              "ts": {
                "order": "asc"
              }
            }
          ]
        }
      ]
    }
  }
}

Below is the error:

{
    "error": {
        "root_cause": [
            {
                "type": "parsing_exception",
                "reason": "[range] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
                "line": 1,
                "col": 155
            }
        ],
        "type": "x_content_parse_exception",
        "reason": "[1:155] [bool] failed to parse field [must]",
        "caused_by": {
            "type": "parsing_exception",
            "reason": "[range] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
            "line": 1,
            "col": 155
        }
    },
    "status": 400
}

CodePudding user response:

If Elasticsearch generated mapping for your index, than you will have .keyword field for your number text field and on that you can make prefix query to get expected result.

{
    "query": {
        "prefix": {
            "number.keyword": "ARK"
        }
    }
}

Update:

{
    "query": {
        "bool": {
            "must": [
                {
                    "prefix": {
                        "number.keyword": "ARK"
                    }
                },
                {
                    "range": {
                        "date_1": {
                            "gte": "2022-01-01 01:00:00",
                            "lte": "2022-03-10 01:00:00"
                        }
                    }
                }
            ]
        }
    },
    "sort": [
        {
            "date_1": {
                "order": "asc"
            },
            "date_2": {
                "order": "asc"
            },
            "ts": {
                "order": "asc"
            }
        }
    ]
}
  • Related