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?

Shubham A.
  • 2,446
  • 4
  • 36
  • 68

1 Answers1

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"
            ]
          }
        }
      ]
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • 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. – Shubham A. Jul 08 '17 at 08:45
  • Try with lowercase `biology` and `chemistry` – Val Jul 08 '17 at 08:48
  • Yes, that's because the `majorSubject` field is an analyzed string and henced the indexed tokens were lowercased. – Val Jul 08 '17 at 08:57
  • 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 ! – Shubham A. Jul 08 '17 at 09:02