5

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

例如:我有一个搜索表单,它填充对象字段,如下所示。然后我想做的是根据用户填写表格的任何内容来搜索弹性搜索。

即:下面,我想通过 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;
            }
        }
    }
}
4

1 回答 1

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

于 2013-10-01T21:09:41.527 回答