如何在另一个应用程序中的一个应用程序中使用弹性搜索索引

时间:2016-04-29 10:17:41

标签: c# asp.net .net elasticsearch nest

我有一个名为zzz的索引的应用程序,我将少量文档编入索引。

        string configvalue1 = ConfigurationManager.AppSettings["http://localhost:9200/"];
        var pool = new SingleNodeConnectionPool(new Uri(configvalue1));
        var defaultIndex = "zzz";

        **settings = new ConnectionSettings(pool)
         .DefaultIndex(defaultIndex)
         .MapDefaultTypeNames(m => m.Add(typeof(Class1), "type"))
         .PrettyJson()
         .DisableDirectStreaming();
        client = new ElasticClient(settings);**


        if (client.IndexExists(defaultIndex).Exists && ConfigurationManager.AppSettings["syncMode"] == "Full")
        {
            client.DeleteIndex(defaultIndex);
            client.CreateIndex(defaultIndex);
        }

        return client;

现在在一个全新的应用程序中,我必须检查zzz是否存在,并将其用于某些搜索操作。我是否还必须编写上述代码中**之间的所有内容,或者只是连接到池并检查索引?

这是我的看法:

        configvalue1 = ConfigurationManager.AppSettings["http://localhost:9200/"];

        var pool = new SingleNodeConnectionPool(new Uri(configvalue1));
        settings = new ConnectionSettings(pool);
        client = new ElasticClient(settings);

        // to check if the index exists and return if exist
        if (client.IndexExists("zzz").Exists)
        {
            return client;
        }

只是添加上述问题:

我想在编制索引之前实现这样的条件:

Index doesnt exist && sync mode == full  --> Create index
Index exist && sync mode==full           --> Delete old index and create a new
Index doesnt exist && sync mode == new   --> Create index
Index exist && sync mode==new            --> Use the existing index

TIA

1 个答案:

答案 0 :(得分:1)

您至少需要

string configvalue1 = ConfigurationManager.AppSettings["http://localhost:9200/"];
var pool = new SingleNodeConnectionPool(new Uri(configvalue1));
var defaultIndex = "zzz";

var settings = new ConnectionSettings(pool)
 .DefaultIndex(defaultIndex);

var client = new ElasticClient(settings);

if (!client.IndexExists(defaultIndex).Exists && 
    ConfigurationManager.AppSettings["syncMode"] == "Full")
{
    // do something when the index is not there. Maybe create it?
}

如果你打算在这个应用程序中使用Class1,并且不想在所有请求中指定它的类型,那么添加

.MapDefaultTypeNames(m => m.Add(typeof(Class1), "type"))

连接设置。

使用

.PrettyJson()

这对于开发目的很有用,但我不建议在生产中使用,因为所有请求和响应都会更大,因为json将缩进。

同样,

.DisableDirectStreaming()

再次,我不建议在生产中使用它,除非您需要记录来自应用程序端的所有请求和响应;此设置会导致所有请求和响应字节在MemoryStream中缓冲,以便可以在客户端外部读取它们,例如,在OnRequestCompleted中。

More details on the settings can be found in the documentation.