我有一些需要导入到elasticsearch的json文件。我使用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文件?
假设sample.json
是具有批量API有效结构的JSON文件,则可以使用以下方式发送请求:>
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,则可以考虑批量读取行对(批量操作和文档)中的文件,并作为多个批量请求发送。