Home > Net >  Check if a List contains an object with a certain value using Nest ElasticSearch
Check if a List contains an object with a certain value using Nest ElasticSearch

Time:11-22

I'm trying to build a filter to my BoolQuery.

the response object contians an object whic contains 2 properties, a bool and a list of another object like this :

responsObject : {

   innerObject :  {
        myinnerObjectBoolProperty: Bool,
        myinnerObjectListProperty : [
            {
                innerObjectType: myEnum,
                // otherProperties
            },
            {
                innerObjectType: myEnum,
                // otherProperties
            }
            
        ]
    } ,
     // other properties
}

I have a method that returns an IEnumerable<QueryContainer> to build a filter for a query after i build the filters i assign them t a BoolQuery's Must BoolQuery bQuery property and I assign that BoolQuery to a SeachRequest's Query property and pass it to the ElasticClient's Search method

var searchRequest = new SearchRequest()
                   {
                       Query = bQuery,
                    // other assignments
                   };
var response = client.Search<responsObject >(searchRequest);

inside the method mentioned above the
filtering through the bool property is working fine like this:

 if (filterValuesList.Contains("myBoolProperty", StringComparer.OrdinalIgnoreCase))
               {
                   var termQuery = new TermQuery()
                   {
                       Field = "innerObject.myBoolProperty",
                       Value = "true"
                   };
                   queries.Add(termQuery);
               }

but what i'm trying to do is to filter objects that have a certain vaule in myEnum.

 var termQuery = new TermQuery()
                   {
                       Field = "innerObject.myinnerObjectListProperty.innerObjectType",
                       Value = "certainType"
                   };

but it doesn't work when I do it like that. simply what I'm truing to achieve is an equivalent to this LINQ statment:

var result = responsObjects.Where(i =>i.innerObject.myinnerObjectListProperty.Any(p => p.innerObjectType == innerObjectType.CertainType));

CodePudding user response:

I figured out what the problem was. I had an attribute on myEnum property to convert the enum to string like : [JsonConverter(typeof(StringEnumConverter))] so I thought that I should pass the string value of the enum. I tried passing the underlying type of the enum (which is int) so it worked like a charm

  • Related