我正在尝试使用Nest将多个记录插入数据库。使用IndexMany类插入确实可以,但是我还需要通过json字符串插入对象。
我确实在github上进行了查找,并找到了一些如何使用RAWclient的示例。在代码示例下面,我插入json。
> var twitter = _jsonData; > var result = client.Raw.BulkPost( > new { twitter } > , qs => qs > //.Replication(ReplicationOptions.Async) > .Refresh(true) );
一些其他信息:
jsondata:
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批量操作。请参阅文档。
在批量请求中,每个数据对象都应带有命令,因为单个批量请求可以包含插入,更新或删除,而不仅仅是插入。所以你的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");