Home > Back-end >  How to filter result set of elasticsearch from another bool condition
How to filter result set of elasticsearch from another bool condition

Time:05-21

I have to fetch data from API which use ElasticSearch. The conditions of data fetching are firstname should start with given string and company status should be active,

so I have used the below query

"span_first": {
            "match": {
                "span_term": {
                    "employee.firstname": "tas"
                }
            },
            "end": 1
        }

to match firstname and now i need to filter the data from companyStatus,

"bool": {
            "must": [
                {
                    "match": {
                        "employee.companyStatus": "Active"
                    }
                }
            ]
        }

I'm trying to plug the above bool query into the span_first query

but I have no idea how to do it,

Can someone help me to create the query, sorry if this is a dumb question, I'm totally new to Elasticsearch.

CodePudding user response:

You can try to use Term Query for filter status and Match Query for search terms.

GET edx_test/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "employee.companyStatus": "Active"
          }
        }
      ],
      "must": [
        {
          "match": {
            "employee.firstname": "tas"
          }
        }
      ]
    }
  }
}

Read more:

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

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

CodePudding user response:

If both the span_first and match query must be true then you can have both the queries in a must clause like below:

GET test_index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "employee.companyStatus": "Active"
          }
        },
        {
          "span_first": {
            "match": {
              "span_term": {
                "employee.firstname": "tas"
              }
            },
            "end": 1
          }
        }
      ]
    }
  }
}
  • Related