1

I need to get the documents from ES using NEST client with multiple like conditions on a single field.

My query is as:

SELECT * FROM Customer WHERE CustomerName LIKE '%john%' OR CustomerName Like '%george%'

My elastic search NEST query (for single like operation)is as:

var customers= ElasticSearchHelper.ElasticClient.SearchAsync<Customer>(body => body
                .Take(100000)
                .Filter(f => f
                    .And
                    (
                       fs=> fs.Query(q=> .QueryString(qs => qs
                                .Query("*" + SearchText + "*")
                                .OnField(new string[] { "FirstName"})
                                .DefaultOperator(Operator.or)
                                .MinimumShouldMatchPercentage(100)
                                .AnalyzeWildcard(true)))
                    )));
            return customers.Documents;

How can I do this with multiple like operation on a single field? Please guide me what I am doing wrong.

1 Answer 1

2

What you need to use is an OR filter combined with a Regex filter:

SearchDescriptor<T> searchDescriptor = new SearchDescriptor<T>();
FilterDescriptor<T> filterDescriptor = new FilterDescriptor<T>();

FilterContainer filterContainer1 = new FilterContainer();
filterContainer1 = filterDescriptor.Regexp(rg => 
                    rg.OnField("CustomerName").Value(".*" + "john" + ".*"));

FilterContainer filterContainer2 = new FilterContainer();
filterContainer2 = filterDescriptor.Regexp(rg => 
                    rg.OnField("CustomerName").Value(".*" + "george" + ".*"));

searchDescriptor.Filter(flt => 
            flt.Or(filterContainer1, filterContainer2));

var resulet = this.ElasticClient().Search<T>(body => searchDescriptor);

Will produce the below query (T is the type of your document):

  {
      "filter": {
        "or": {
          "filters": [
            {
              "regexp": {
                "CustomerName": {
                  "value": ".*john.*"
                }
              }
            },
            {
              "regexp": {
                "CustomerName": {
                  "value": ".*doe.*"
                }
              }
            }
          ]
        }
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

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.