#StackBounty: #c# #elasticsearch #nest NEST: Find Best match using elastic search

Bounty: 50

I am trying to write a query to find the best match. I have an index with the structure below.

  public class UserProfileSearch
    {
        public int Id { get; set; }
        public int Sex { get; set; }
        public int Age { get; set; }
        public int MaritalStatus { get; set; }
        public int CountryLivingIn { get; set; }
        public double Height { get; set; }
        public double BodyWeight { get; set; }
    ...
   }

When I start my search I use different parameters. I get the search parameters as an object which has the structure below.

  public class UserPreference
    {
        public int Id { get; set; }
        public int FromAge { get; set; }
        public int ToAge { get; set; }
        public int FromHeight { get; set; }
        public int ToHeight { get; set; }
        public string MartialStatus { get; set; } // This will have id in comma separated form: 11,23,24..
        public string CountriesLivingIn { get; set; } // This will also have id in comma separated form: 11,23,24..
        public string Sexes { get; set; }
        ...
     }

I am trying to achieve like below.

 QueryContainer qCs = null;
            userPartnerPreference.CountriesLivingIn.Split(",").ToList().ForEach(id =>
            {
                qCs |= new TermQuery { Field = "countryLivingIn ", Value = int.Parse(id) };
            });
 QueryContainer qSs = null;
userPartnerPreference.MartialStatus.Split(",").ToList().ForEach(id =>
              {
                  qSs &= new TermQuery { Field = "maritalStatus", Value = int.Parse(id) };
              });

 var searchResults = await _elasticClient.SearchAsync<UserProfileSearch>(s => s
              .Query(q => q
                   .Bool(b => b
                      .Must(qSs)
                      .Should(
                              bs => bs.Range(r => r.Field(f => f.Age).GreaterThanOrEquals(userPartnerPreference.FromAge).LessThan(userPartnerPreference.ToAge)),
                              bs => bs.Range(r => r.Field(f => f.Height).GreaterThanOrEquals(userPartnerPreference.FromHeight).LessThanOrEquals(userPartnerPreference.ToHeight)),
                              bs => bs.Bool(bsb=>bsb.Should(qCs))
                             )
                         )
                      )
                   ); 

I basically want to find the best match result based on the parameters passed ordered by highest number of fields matched. I’m new to elastic search so is this the way to do it?

Note: I have other fields that I need to match. There are around 15 field, which I am planning to have inside should like age and height.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.