Search code examples
node.jselasticsearchstrapi

search multiple field as regexp query in elasticsearch


I am trying to search by different fields such as title and description. When i type keywords, elasticseach must found something if description or title includes that i typed keywords. This is my goal. How can i reach my goal?

You can see the sample code that i used for one field.

  query: {
          regexp: {
            title: `.*${q}.*`,
          },
        },

I also tried below one but it gave syntax error.

  query: {
          regexp: {
            title: `.*${q}.*`,
          },
          regexp: {
            description: `.*${q}.*`,
          },
        },

Solution

  • To do so, you need to use a bool query.

    GET /<you index>/_search
    {
      "query": {
        "bool": {
          "should": [
            {
              "regexp": {
                "title": ".*${q}.*"
              }
            },
            {
              "regexp": {
                "description": ".*${q}.*"
              }
            }
          ]
        }
      }
    }
    

    You can find the documentation => [doc]