How to compare 2 array entries in nested doc when value doesn't matter


(Volker Kueffel) #1

I'm trying to compare 2 entries in an array of nested documents in ElasticSearch.

Imagine this document structure:

{
	"_source": {
		"id": "something",
		"content": [{
			"field1": "value1",
			"text": "The quick brown fox jumps over the lazy dog",
			"rc": 10
		}, {
			"field1": "value2",
			"text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit...",
			"rc": 20
		}, {
			"field1": "value3",
			"text": "Etaoin shrdlu",
			"rc": 30
		}]
	}
}

The content array can potentially have many entries.

Now I want to write a query checks for 2 entries to be present; specified by term/phrase queries against "field1" and "text". However, the document should only match, if the value for "rc" of one nested documents is smaller than the the value for the other.

So in pseudo code, I would want this to match:

field1="value1" AND text~="fox" and field1="value3" and text~="shrdlu" and match[1].rc<match[2].rc

I can match the text conditions above with a bool query, but I have not found a solution to compare the 2 rc values of the matched array entries:

{
	"query": {
		"bool": {
			"must": [{
					"nested": {
						"path": "content",
						"query": {
							"bool": {
								"must": [{
										"match_phrase": {
											"content.text": {
												"query": "fox",
											}
										}
									},{
										"term": {
											"content.field1": {
												"value": "value1",
											}
										}
									}
								]
							}
						}
					}
				},
				{
					"nested": {
                        "path": "content",
						"query": {
							"bool": {
								"must": [{
										"match_phrase": {
											"content.text": {
												"query": "shrdlu",

											}
										}
									},{
										"term": {
											"content.field1": {
												"value": "value3",
											}
										}
									}
								]
							}
						}
					}
				}
			]
		}
	}
}

I would sort of need to use the inner hits (if enabled) in a post_filter(), but those seem to be not available.

Also posted on SO: https://stackoverflow.com/questions/45380096/elastic-how-to-compare-2-array-entries-in-nested-doc-when-value-doesnt-matter


(system) #2

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