Search code examples
c#databaseelasticsearchnest

Do I need to create a Type for Nest Search?


I see examples like:

var result = this._client.Search(s => s
.Index("my-index")
.Type("my-type")
 .Query(q=> ....)
 .Filter(f=> ....)         
);

But when I use this I get:

The type arguments for method 'Nest.ElasticClient.Search<T>(System.Func<Nest.SearchDescriptor<T>,Nest.SearchDescriptor<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.   

I have lots of different types and I don't want to create classes for all of them. Can I use NEST and it's search without types like Search<MyType>?

Thanks


Solution

  • I have successfully used Search<dynamic> to avoid needing to be dependent upon a specific type. Then when I get my results back I can examine them and cast/convert into a specific POCO if desired.

    I use something like the following:

    var result = client.Search<dynamic>(s => s
         .Index("myIndex")
         .AllTypes()
         .Query(q => ...)
         .Filter(f => ...)
    );
    
    foreach (var hit in result.Hits.Hits)
    {
         //check hit.Type and then map hit.Source into the appropriate POCO.
         // I use AutoMapper for the mapping, but you can do whatever suits you.
         if (string.Compare(hit.Type, "myType", StringCompare.OrdinalIgnoreCase) == 0)
         {
               var myType = AutoMapper.Mapper<MyType>(hit.Source);
         }
    }