2

I want to match records against a query string, so I wrote the following query which is working fine:

{
  "query": {
    "query_string": {
      "fields": ["rollno","name"],
        "query": "*John*"
      }
  }
}

Now, apart from matching the fields, I want to implement IN query against another field as well. I tried this query, as:

{
"query": {
    "query_string": {
        "fields": ["rollno", "name"],
        "query": "*John*"
    },
    "match": {
        "majorSubject": ["Biology", "Chemistry"]
    }
  }
}

All I get is search_parse_exception.

How to this IN operation?

1 Answer 1

2

You need to use a bool/must query in order to combine both sub-queries:

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "rollno",
              "name"
            ],
            "query": "*John*"
          }
        },
        {
          "terms": {
            "majorSubject": [
              "Biology",
              "Chemistry"
            ]
          }
        }
      ]
    }
  }
}

if the majorSubject field is an analyzed string, use lowercase terms instead:

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "rollno",
              "name"
            ],
            "query": "*John*"
          }
        },
        {
          "terms": {
            "majorSubject": [
              "biology",
              "chemistry"
            ]
          }
        }
      ]
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

When I do this, query doesn't return any results at all, when I actually have matching data. Please see my answer how I solved this. That may have side-affects I do not know right now.
Try with lowercase biology and chemistry
Yes, that's because the majorSubject field is an analyzed string and henced the indexed tokens were lowercased.
I understand. When I defined my mapping, I should have specified majorSubject as non_analyzed so that only exact values are matched against it as in my case, majorSubject will have some fixed values only. But right now, anatomy will match both Social anatomy and Biological anatomy, definitely a problem. Thanks for the insight !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.