From 00431fc79f07cf21e688070419b19944fae8cf6c Mon Sep 17 00:00:00 2001 From: Hardy Date: Thu, 27 May 2021 22:06:02 +0800 Subject: [PATCH] feat: Support Nested for joining queries. --- query_joining.go | 40 ++++++++++++++++++++++++++++++++++++++++ query_joining_test.go | 22 ++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 query_joining.go create mode 100644 query_joining_test.go diff --git a/query_joining.go b/query_joining.go new file mode 100644 index 0000000..6655de9 --- /dev/null +++ b/query_joining.go @@ -0,0 +1,40 @@ +package esquery + +// NestedQuery represents a query of type nested as described in: +// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html +type NestedQuery struct { + path string + query Mappable + scoreMode string + ignoreUnmapped bool +} + +func Nested(path string, query Mappable) *NestedQuery { + return &NestedQuery{ + path: path, + query: query, + } +} + +func (n *NestedQuery) ScoreMode(mode string) *NestedQuery { + n.scoreMode = mode + return n +} + +func (n *NestedQuery) IgnoreUnmapped(val bool) *NestedQuery { + n.ignoreUnmapped = val + return n +} + +// Map returns a map representation of the query, thus implementing the +// Mappable interface. +func (n *NestedQuery) Map() map[string]interface{} { + innerMap := map[string]interface{}{"path": n.path, "query": n.query.Map()} + if n.scoreMode != "" { + innerMap["score_mode"] = n.scoreMode + } + if n.ignoreUnmapped == true { + innerMap["ignore_unmapped"] = n.ignoreUnmapped + } + return map[string]interface{}{"nested": innerMap} +} diff --git a/query_joining_test.go b/query_joining_test.go new file mode 100644 index 0000000..7b4636b --- /dev/null +++ b/query_joining_test.go @@ -0,0 +1,22 @@ +package esquery + +import ( + "testing" +) + +func TestNested(t *testing.T) { + runMapTests(t, []mapTest{ + { + "Nested Query", + Nested("dns_values", Term("dns_values.type", "A")).ScoreMode("max").IgnoreUnmapped(true), + map[string]interface{}{ + "nested": map[string]interface{}{ + "path": "dns_values", + "query": Term("dns_values.type", "A").Map(), + "score_mode": "max", + "ignore_unmapped": true, + }, + }, + }, + }) +}