Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch Go nested query

I'm using olivere's elastic Go library to run Elastic queries - https://godoc.org/github.com/olivere/elastic#NestedQuery

The data I'm trying to query on looks like this:

                "_source": {
                    "field1": "randVal1",
                    "field2": "randVal2",
                    "nestedfield": {
                        "ind1": "val1"
                    }
                }

I'm trying to run a query on the nestedfield using the NestedQuery call from the Elastic Go library like so:

aquery := elastic.NewTermQuery("ind1", "val1")
query := elastic.NestedQuery("nestedfield", aquery)

But I get an error stating:

too many arguments to conversion to NestedQuery

I'm trying to retrieve all documents where the ind1 of nestedfield is val1. Would appreciate any help in constructing this query.

EDIT:

I changed it to NewNestedQuery and now it doesn't give that error. However, it is not returning any results, even though that document exists in the index and I am able to query on the non-nested fields.

I tried this:

aquery := elastic.NewTermQuery("ind1", "val1")
query := elastic.NewNestedQuery("nestedfield", aquery)

And this:

query := elastic.NewNestedQuery("nestedfield", elastic.NewMatchQuery("nestedfield.ind1", "val1"))

But they both give 0 results. Any idea what I'm doing wrong?

EDIT #2

The mapping is:

"field1": { "type": "string" },
"field2": { "type": "string" },
"nestedfield": {
                    "type": "nested"
                }

What eventually worked was this:

query := elastic.NewMatchQuery("nestedfield.ind1", "val1")

I was able to add additional fields to 'nestedfield' and do queries like:

query := elastic.NewBoolQuery().Filter(elastic.NewMatchQuery("nestedfield.ind1", "val1"), elastic.NewMatchQuery("nestedfield.ind2", "val2"))
like image 915
covfefe Avatar asked Sep 26 '17 18:09

covfefe


1 Answers

Looks like that should be:

q := elastic.NewTermQuery("nestedfield.ind1", value)
nq := elastic.NewNestedQuery("nestedfield", q)
  • NestedQuery is a type, not a function.
  • NewTermQuery needs to take a value from the json, not a const string
  • You'll need to parse your source json to get the value from ind1

Edited to fix NewTermQuery too as per comments below. If that still doesn't work provide the full code you're using to parse source and get the error as you don't give enough detail here to guess at the problem.

like image 128
Kenny Grant Avatar answered Oct 13 '22 04:10

Kenny Grant