Search code examples
asp.netelasticsearchnest

How can add several fields to NEST?


I use Generic and Reflection, so the main problem is add several fields. When i use this code with one field it OK but when i try somehow add new fields it doesn't work:

  public static ISearchResponse<T> PartSearch<T>(ElasticClient client, string query, List<string> fieldList = null, int from = 0, int size = 1) where T : class
    {
        if (client == null)
            throw new ArgumentNullException();
        if (String.IsNullOrEmpty(query))
            throw new ArgumentNullException();
        ISearchResponse<T> results;
        if (fieldList == null)
        {
            results = client.Search<T>(q =>
                q.Query(q =>
                    q.QueryString(qs => qs.Query(query)) 
                ).From(from).Size(size)
            );
        }
        else
        {
            results = client.Search<T>(q =>
                 q.Query(q => q
                     .QueryString(qs =>
                     {   
                         //This place where i try to add several fields
                         List<Field> fildArray = new List<Field>(); 
                         foreach (var arg in fieldList)
                         {
                             var fieldString = new Field(typeof(T).GetProperty(arg));
                             fildArray.Add(fieldString); 
                         }

                         qs.Fields(f => f.Field(fildArray)); 

                         qs.Query(query);

                         return qs;
                     })
                 ).From(from).Size(size)
             );

        }

        return results;
    }

Solution

  • I created an example using Lenient() that can help you with your question:

    https://github.com/hgmauri/elasticsearch-with-nest/blob/master/src/Sample.Elasticsearch.Domain/Abstractions/NestExtensions.cs