我正在尝试使用 Nest 将多条记录插入到我的数据库中。使用 IndexMany 类插入确实有效,但是我还需要通过 json 字符串插入对象。
我确实在 github 上查找过,并找到了一些如何使用 RAWclient 的示例。在代码示例下面我插入了我的 json。
> var twitter = _jsonData;
> var result = client.Raw.BulkPost(
> new { twitter }
> , qs => qs
> //.Replication(ReplicationOptions.Async)
> .Refresh(true) );
一些附加信息:
json数据:
tweet tweet1 = new tweet { id = "104", name = "test104", lastname = "test107" }; //ect....
List<tweet> data; //multiple tweet objects are added
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var twitter:
{
"twitter": "[{'name':'test104','lastname':'test107','id':'104'},{'name':'test105','lastname':'test108','id':'105'},{'name':'test106','lastname':'test109','id':'106'}]"
}
我从数据库收到的结果:
{"error":"Unexpected end-of-input: expected close marker for OBJECT (from [Source: [B@10893e4; line: 1, column: 0])\n at [Source: [B@10893e4; line: 2, column: 3]"}
有人知道问题出在哪里吗?或者我的 json/代码片段中缺少什么?
最佳答案
您的 json 对于 Elasticsearch 批量操作不正确。请参阅documentation .
在批量请求中,每个数据对象前面都应该有一个命令,因为单个批量请求可以包含插入、更新或删除,而不仅仅是插入。 所以你的 json 应该看起来像
{ "index" : { "_index" : "twitter", "_type" : "tweets" } }\n
{'name':'test104','lastname':'test107','id':'104'}\n
{ "index" : { "_index" : "twitter", "_type" : "tweets" } }\n
{'name':'test105','lastname':'test108','id':'105'}\n
{ "index" : { "_index" : "twitter", "_type" : "tweets" } }\n
{'name':'test106','lastname':'test109','id':'106'}\n
为了减少重复命令的开销,您可以将一些参数移动到请求 uri。那么json可以更短:
{ "index" : { } }\n
{'name':'test104','lastname':'test107','id':'104'}\n
在 IRawElasticClient 中,这意味着将它们移至 BulkPost 参数。
var result = client.Raw.BulkPost(new { twitter }, "twitter", "tweets");
关于c# - 如何使用NEST elasticsearch批量插入Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22017858/