Home > Software engineering >  How to search for query in all fields in match using elasticsearch
How to search for query in all fields in match using elasticsearch

Time:09-27

I'm using elasticsearch in my react app and I want to know the correct way or format to search for word(query) in all fields

this is my get request

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "category": {
              "query": "الأنظمة",
              "operator": "and"
            }
          }
        }
      ],
      "filter": [
        {
          "range": {
            "date": {
              "gte": "1970-01-01",
              "lt": "2400-01-01"
            }
          }
        }
      ]
    }
  },
  "size": "1000",
  "sort": [
    {
      "date": "desc"
    }
  ]
}

CodePudding user response:

I solve this by

query_string

:

{
  "query": {
    "bool": {
              "filter": [
        {
          "range": {
            "date": {
              "gte": "1970-01-01",
              "lt": "2400-01-01"
            }
          }
        }
      ],
      "must": [
         {
          "query_string": {
              "query": "نظام"
            }
        }
      ]
    }
  },
  "size": "1000",
  "sort": [
    {
      "date": "desc"
    }
  ]
}

CodePudding user response:

Really the default behavior of ElasticSearch is to do what you are trying to do, but you have added complexity that was not needed.

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html

The query DSL is well documented and there are a great number of options for doing such a search.

The multi-match query is what you are looking for

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html

This version will search just a couple fields.

{
  "query": {
    "bool": { 
      "must": [{
        "multi_match": {
          "query": "الأنظمة",
          "fields": [field1, field2]
        }
      }],
      "filter": [
        {"range": {"date": {"gte": "1970-01-01", "lt": "2400-01-01" } } }
      ] 
    }
  },
  "size": "1000",
  "sort": [{ "date": "desc" }]
}

If you want to match all fields omit the fields parameter. This is however limited to 1024 fields.

{
  "query": {
    "bool": { 
      "must": [{
        "multi_match": { "query": "الأنظمة" }
      }],
      "filter": [
        {"range": {"date": {"gte": "1970-01-01", "lt": "2400-01-01" } } }
      ] 
    }
  },
  "size": "1000",
  "sort": [{ "date": "desc" }]
}
  • Related