Search code examples
c#elasticsearchnest

Generic Elastic Search Method c#


I'm using the Nest.

https://www.nuget.org/packages/NEST/6.1.0

I have the following code:

    public class foo
    {
        public Guid id { get; set; }
    }

    public class foo2
    {
        public Guid id { get; set; }
    }


    public IReadOnlyCollection<T> GetDocumentAsync<T>(Guid id) where T: class
    {
        var searchResponse = _client.Search<T>(s => s
            .Query(q => q
                .Match(m => m
                    .Field(f => f.id) //f.id is not a property of T
                    .Query(id.ToString())
                )
            )
        );

        return searchResponse.Documents;
    }

Question: How can I pass the field in as Id? I am aware I could make an interface however I don't have access to the classes. Is there another way to map it?


Solution

  • T is generic, if you want to use specific properties, you need to use a non-generic method or add a constraint that gives you the Id property. For example, have an interface like this:

    public interface IHasId
    {
        Guid id { get; }
    }
    

    Which makes your models look like this:

    public class foo : IHasId
    {
        public Guid id { get; set; }
    }
    
    public class foo2 : IHasId
    {
        public Guid id { get; set; }
    }
    

    And now your method would have an updated constraint:

    public IReadOnlyCollection<T> GetDocumentAsync<T>(Guid id)
        where T : class, IHasId // <--- Add this
    {
        // Snip
    }