使用Nest进行弹性搜索

时间:2013-10-01 21:00:01

标签: c# elasticsearch nest

我正在处理下面的代码,我想要做的是按对象本身进行查询。

例如:我有一个搜索表单,填充下面的对象字段。那么我想要做的是根据填写表单的用户搜索弹性搜索。

ie:在下面,我想通过searchItem对象查询索引。我怎么能轻易做到?

 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 个答案:

答案 0 :(得分:5)

你不能:)

NEST无法根据部分填充的POCO推断如何最佳查询。 OR或AND是否应该执行嵌套的术语查询或包含在has_child中的术语查询?你抓住了我的漂移。

Nest确实有一个名为无条件查询的灵活功能,允许您像这样写出整个查询:

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
    )
)

当NEST发现传递给Term的参数为null或为空时,它只是不会呈现查询的那一部分。

在此处详细了解此功能的工作原理http://nest.azurewebsites.net/concepts/writing-queries.html