0

我有一些 json 文件需要导入到 elasticsearch。

我使用 curl api。以下是示例,对我来说效果很好。

curl -XPOST http://localhost:9200/index_local/_doc/_bulk -H "Content-Type: application/json" --data-binary @sample.json


我使用HttpWebRequest进行模拟,它对我来说也很好。

public void Post(string fileName)
{
    try
    {
        // get the byte array 
        var data = File.ReadAllBytes(fileName);

        // create HttpRequest
        var httpRequest = (HttpWebRequest)WebRequest.Create(@"http://localhost:9200/index_local/_doc/_bulk");
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/json";
        httpRequest.ContentLength = data.Length;

        // set the file byte array to the stream
        using (var requestStream = httpRequest.GetRequestStream())
        {
            requestStream.Write(data, 0, data.Length);
        }

        // get the response
        using (var response = httpRequest.GetResponse() as HttpWebResponse)
        {
            using (var responseStream = new StreamReader(response.GetResponseStream()))
            {
                // read the result
                Console.WriteLine(responseStream.ReadToEnd());
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

但我找不到带有 elasticsearch.net 的导入 json 文件的批量 api。

是否有一些等于HttpWebRequest的函数可以将 json 文件发布到 elasticsearch ?

elasticsearch.net 库 ElasticLowLevelClient 或 ElasticClient 是否支持使用 btye 数组导入 json 文件?

4

1 回答 1

1

假设sample.json是一个 JSON 文件,该文件具有适用于批量 API 的有效结构,您可以使用以下命令发送请求

var client = new ElasticClient();
var bytes = File.ReadAllBytes("sample.json");

var bulkResponse = client.LowLevel.Bulk<BulkResponse>(
    bytes,
    new BulkRequestParameters
    {
        RequestConfiguration = new RequestConfiguration
        {
            RequestTimeout = TimeSpan.FromMinutes(3)
        }
    });

if (!bulkResponse.IsValid)
{
    // handle failure
}

这会为此请求设置特定的请求超时,如果批量大于正常请求(通常是这样),您可能会将其设置为大于正常的值。如果sample.json大于约 5MB,您可能会考虑分批读取行对(批量操作和文档)的文件,并作为多个批量请求发送。

于 2019-11-24T22:46:51.933 回答