iamatsundere181
iamatsundere181

Reputation: 1409

How to search on queried documents in Elasticsearch?

I am a newbie in Elasticsearch and I am facing a problem. My task is searching on a set of documents. For example, I have data with struct like this:

type Doc struct{
   id string
   project_id string
   code string
   name string
   status string
}

But the difficult thing is I what to get all the documents with project_id=abc then search on them by any other fields (code,name,status) that match the keyword 'test' (for example). How can I do that in Elasticsearch query, please help me!

Thanks.

Upvotes: 0

Views: 262

Answers (3)

iamatsundere181
iamatsundere181

Reputation: 1409

Here is my solution

GET /[index_name]/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "some text here"
          }
        }
      ],
      "filter": [
        {
          "term": {
            "project_id.keyword": "abc"
          }
        }
      ]
    }
  }
}

Upvotes: 0

elham
elham

Reputation: 11

I think maybe using Logstash and filtering some data can help you.

Upvotes: 0

Bhavya
Bhavya

Reputation: 16172

You can use a boolean query that matches documents matching boolean combinations of other queries.

must is the same as logical AND operator and should is the same as logical OR operator

Adding a working example with index data, search query, and search result

Index Data:

{
  "id": 2,
  "project_id":"abc",
  "code": "a",
  "name":"bhavya",
  "status":"engineer"
}
{
  "id": 1,
  "project_id":"abc",
  "code": "a",
  "name":"bhavya",
  "status":"student"
}
{
  "id": 3,
  "project_id":"def",
  "code": "a",
  "name":"deeksha",
  "status":"engineer"
}

Search Query:

The given query satisfies the condition that "project_id" = "abc" AND "name" : "bhavya" AND "status":"student"

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "project_id": "abc"
          }
        },
        {
          "match": {
            "name": "bhavya"
          }
        },
        {
          "match": {
            "status": "student"
          }
        }
      ]
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "stof_64274465",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.7021472,
        "_source": {
          "id": 1,
          "project_id": "abc",
          "code": "a",
          "name": "bhavya",
          "status": "student"
        }
      }
    ]

Upvotes: 1

Related Questions