2

I'm using Nest to connect to ElasticSearch and perform some queries. Until now, I've been able to get the results I'm asking for given a single wildcard query as below:

var searchResults = _client.Search<MyIndexable>(
            body =>
            body
                .Index("someIndex")
                .Query(
                    query =>
                    query.QueryString(
                        qs => qs.
                                  OnFields(f => f.Title, f => f.Description)
                                  .Query(searchTerm + "*"))));

But now I need to add additional conditions to my query for a certain usecase.

What I need is not only to query by [searchTerm]* but also two other fields matching:

  • searchTerm + "*"
  • field1 = "some string"
  • field2 = "some Guid"

I'm sure there must be a way to do this in elastic search (using Nest) but I haven't been able to find it.

I know I can add the two additional fields to the index (as in someIndex_field1_field2) and that is definitely an option for me since field1 and field2 are decent partitions (and in fact, it may be a much better option to allow better partitioning) but I just wanted to see if there was a way to avoid doing this and instead, if it was possible to add multiple conditions to the query.

Does anyone know how to achieve this?

Many thanks,

1 Answer 1

5

Assuming field1 and field2 are just another fields like Title and Description, you can use bool must query to achieve what you want.

var searchResults = _client.Search<MyIndexable>(s => s
    .Query(q => q
        .Bool(b => b
            .Must(
                subQuery => subQuery.QueryString(qs => qs.OnFields(f => f.Title, f => f.Description).Query(searchTerm + "*"")),
                subQuery => subQuery.Term(f => f.field1, "some string"),
                subQuery => subQuery.Term(f => f.field2 , "some Guid")))));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I'll try it later tonight when I get home. One question: Is it better (stability wise, performance wise, etc.) doing it this way by matching all fields or would it be better to use a different index for each combination of field1 + field2 if the combination has a finite subset (say 30 different combinations) and then do the matching on the composite index instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.