How to apply logical operators to search query in golang?

Hi,

how can I specify if I want a query to use the AND or OR operator? For a SimpleQuery this is easy, just call DefaultOperator(operator.Operator{"AND"}). But how Do I specify this with a BoolQuery?

What I found is, that I can call an Operator() function on esdsl.NewMultiMatchQuery(), which I already use to search multiple fields for one pattern. But what if I want to search for (e.g.): message=error, tenant=foo? Currently BoolQuery seems to use the OR operator since it returns documents matching `message=error` of any tenant AND documents matching `tenant=foo` for ANY message, but I need AND in this case - or better I need it to be customizable.

Here's the code I have for this so far (just the relevant part):

query := esdsl.NewBoolQuery()

for _, q := range queries {
	filter, err := NewFilter(q)
	if err != nil {
		return nil, err
	}

	// by default we match on a single field
	var match types.QueryVariant = esdsl.NewMatchQuery(filter.term, filter.filter)

	if filter.multi {
		// ok, match across multiple given fields
		match = esdsl.NewMultiMatchQuery(filter.filter).
                Fields(filter.mterm...).Operator(op) // ok
	}

	// apply logic
	switch filter.criteria {
	case Fmustnot:
		query.MustNot(match)
	case Fmust:
		query.Must(match)
	case Fshould:
		query.Should(match)

	// query.DefaultOperator() or something alike?
}

It is possible to add multiple MatchQueries to a BoolQuery, but I was unable to figure out how to specify an operator.

Thanks in advance,
Tom

Hi @scip,

Welcome! You'll see from the bool query documentation that each query under the must clause would equate to an AND clause, compared with should which equates to OR:

|must|The clause (query) must appear in matching documents and will contribute to the score. Each query defined under a must acts as a logical "AND", returning only documents that match all the specified queries.|
| --- | --- |
|should|The clause (query) should appear in the matching document. Each query defined under a should acts as a logical "OR", returning documents that match any of the specified queries.|

So in your case the AND criteria should come under query.Must for example.

Hope that helps!

Hi Carly,

yes, that's it. I already found it myself but forgot to update here. Thanks a lot anyway!

bestm

Tom