Match all nested array terms

Hi!

I have the need to index and search by Question/Answers logic e.g. There is a Question with multiple answers => You can choose many of them e.g. "What languages do You speak?" would allow answers like "English", "German", "French" etc.

So I believe the indexed object would look like this:

{
    "questions":[
        {
            "id":1,
            "answers":[
                10,
                20
            ]
        },
        {
            "id":2,
            "answers":[
                30,
                40
            ]
        }
    ]
}

Now the question is how can I match documents that match e.g. "English" AND "German" for Question with ID 1 AND "Answer A" for Question with ID 2?

I am trying something like https://www.elastic.co/guide/en/elasticsearch/reference/6.2/nested.html but can`t figure out how to define query to match array of values (e.g. answers in my case) (not just single value like Question ID).

Here is the query which seems to work:

{
"query":{
	"bool":{
		"must":[
			{
				"nested":{
					"path":"questions",
					"query":{
						"bool":{
							"must":[
								{
									"term":{
										"questions.id":1
									}
								},
								{
									"term":{
										"questions.answers": 10
									}
								},
								{
									"term":{
										"questions.answers": 20
									}
								}
							]
						}
					}
				}
			},
			{
				"nested":{
					"path":"questions",
					"query":{
						"bool":{
							"must":[
								{
									"term":{
										"questions.id":2
									}
								},
								{
									"term":{
										"questions.answers":90
									}
								}
							]
						}
					}
				}
			}
		]
	}
}

}

What seems odd is that I need to add as many "nested" clauses as many Questions I want to match and also defining Answers as "terms": array fails as it looses nesting so I need to define each and every answer individually as dedicated term. I have a feeling there must be a better way to do this, right?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.