接着上一个文章
21-ElasticSearch使用C#添加文档 http://www.sufeinet.com/thread-24549-1-1.html (出处: 苏飞论坛)
NEST提供两种更新文档的方式,逐条更新和批量更新,函数PopulateIndex用于逐条更新索引,函数BulkPopulateIndex用于批量更新索引; 注意,在更新索引时,高亮显示的代码指定了索引的元字段_id为meetupevent实体的主键eventid;
[C#] 纯文本查看 复制代码 using Nest;
public class ESProvider
{
public static ElasticClient client = new ElasticClient(Setting.ConnectionSettings);
public static string strIndexName = @"meetup".ToLower();
public static string strDocType = "events".ToLower();
public bool PopulateIndex(MeetupEvents meetupevent)
{
var index = client.Index(meetupevent,i=>i.Index(strIndexName).Type(strDocType).Id(meetupevent.eventid));
return index.Created;
}
public bool BulkPopulateIndex(List<MeetupEvents> posts)
{
var bulkRequest = new BulkRequest(strIndexName,strDocType) { Operations = new List<IBulkOperation>() };
var idxops = posts.Select(o => new BulkIndexOperation<MeetupEvents>(o) { Id=o.eventid}).Cast<IBulkOperation>().ToList();
bulkRequest.Operations = idxops;
var response = client.Bulk(bulkRequest);
return response.IsValid;
}
}
执行批量更新操作 如果更新的数据量十分庞大,建议,首先对数据源分页,分batch更新ElasticSearch的索引。ElasticSearch在批量索引文档时,如果一批文档数量过大,会导致数据丢失,建议每次索引1000个文档。 [C#] 纯文本查看 复制代码 ESProvider es = new ESProvider();
List<MeetupEvents> pbs = new List<MeetupEvents>();
foreach (DataRow dr in MeetupEventsTable.Rows)
{
MeetupEvents pb = new MeetupEvents();
pb.eventid = long.Parse(dr["EventID"].ToString());
pb.orignalid = dr["OriginalID"].ToString();
pb.eventname = dr["EventName"].ToString();
pb.description = dr["Description"].ToString();
pbs.Add(pb);
}
es.BulkPopulateIndex(pbs);
|