5
votes

I am working on below code, and what I want to do is query by object itself.

For example: I have a search form, that populates objects fields such as below. Then what I want to do is to search Elastic search based on whatever user filled the form with.

ie: below, I want to query the index by searchItem object. How can I do it easily?

 class Program
 {
    static void Main(string[] args)
    {
        var p = new Program();

        var item1 = new Announcement() {Id=1, Title = "john", ContentText = "lorem", Bar =  false, Num =  99, Foo = "hellow"};

        //p.Index(item1, "add");

       var searchItem = new Announcement() {Title="john",Num=99};

        ElasticClient.Search<Announcement>();

        Console.Read();

    }

    public void Index(Announcement announcement, String operation)
    {
        var uriString = "http://localhost:9200";
        var searchBoxUri = new Uri(uriString);

        var settings = new ConnectionSettings(searchBoxUri);
        settings.SetDefaultIndex("test");

        var client = new ElasticClient(settings);

        if (operation.Equals("delete"))
        {
            client.DeleteById("test", "announcement", announcement.Id);
        }
        else
        {
            client.Index(announcement, "test", "announcement", announcement.Id);
        }
    }

    private static ElasticClient ElasticClient
    {
        get
        {
            try
            {
                var uriString = "http://localhost:9200";
                var searchBoxUri = new Uri(uriString);
                var settings = new ConnectionSettings(searchBoxUri);
                settings.SetDefaultIndex("test");
                return new ElasticClient(settings);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
1

1 Answers

5
votes

You can't :)

NEST cannot infer how to best query only based on a partially filled POCO. Should it OR or AND should it do a nested term query or a term query wrapped in a has_child? You catch my drift.

Nest does have a slick feature called conditionless queries that allow you the write out to entire query like so:

ElasticClient.Search<Announcement>(s=>s
    .Query(q=>
        q.Term(p=>p.Title, searchItem.Title)
        && q.Term(p=>p.Num, searchItem.Num)
        //Many more queries use () to group all you want
    )
)

When NEST sees that the argument passed to Term is null or empty it simply wont render that part of the query.

Read more here on how this feature works http://nest.azurewebsites.net/concepts/writing-queries.html