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.

4

1 回答 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.*"
                }
              }
            }
          ]
        }
      }
    }
于 2014-11-03T10:56:35.263 回答