ES4: ElasticSearch uses C # To add and update documents,

Source: Internet
Author: User
Tags dot net

ES4: ElasticSearch uses C # To add and update documents,

This is the fourth article in The ElasticSearch 2.4 series:

Article 1: ES1: Installing ElasticSearch in Windows

Article 2: ES2: ElasticSearch cluster configuration

Article 3: ES3: ElasticSearch Index

Article 4: ES4: use C # To add and update documents for ElasticSearch

 

Full-text search in the ElasticSearch engine is a cool thing, and creating an index is the most important thing and must be carefully designed, we recommend that you use the head plug-in to create index Mapping. For daily updates to index document data, you can use the C # client program to automatically synchronize and update data as planned.

For a database development, I haven't written C # code for a long time, and I am a newbie in dot net. This article briefly shares the use of ElasticSearch.. net client driver to add the code snippet of the document to the index. For more information, see the official manual: Elasticsearch. net and NEST:. NET clients [5.x]» Introduction

1. ElasticSearch's. net client driver

ElasticSearch provides two official websites.. net client driver, in which Elasticsearch. net is a very underlying and flexible client driver. You need to manually create a Request and a Response. NEST is a high-level client, elasticsearch is used internally. net driver, NEST has a query DSL (domain-specific language), which can map all request and response objects for ease of use. The interfaces provided by NEST drivers of different versions vary greatly. After getting familiar with Nest, you can use the Elasticsearch. Net driver to write your own code.

First, download the. net client driver of ElastiSearch, open the Tools menu of VS, use the NuGet Package Manager Console, and enter the command to install NEST:

PM> Install-Package NEST

After the installation, the system references three DLL files. The driver versions installed by the landlord are:

  • Elasticsearch. Net. dll (version 5.0.0.0)
  • Nest. dll (version 5.0.0.0)
  • Newtonsoft. Json. dll (version 9.0.0.0)

2. Simple NEST driverUse

1. Connect to the ElasticSearch engine server

Note: The default index name must be in lowercase. We recommend that you use lowercase letters for the index name, document type name, and field name.

using Nest;    public static class Setting{    public static string strConnectionString=@"http://localhost:9200";    public static Uri Node    {        get        {            return new Uri(strConnectionString);        }    }    public static ConnectionSettings ConnectionSettings    {        get        {            return new ConnectionSettings(Node).DefaultIndex("default");        }    }}

2. Create a data model

Note that the field names of the model are consistent with those in the created index ing. We recommend that you use lowercase letters. The Nest Driver provides model attributes that readers can try.

public class MeetupEvents{    public long eventid { get; set; }    public string orignalid { get; set; }    public string eventname { get; set; }    public string description { get; set; }}

3. Update the document

NEST provides two methods to update documents, one by one and one by one. The PopulateIndex function is used to update indexes one by one. The BulkPopulateIndex function is used to update indexes in batches;

Note: when updating the index, the highlighted Code specifies that the meta field _ id of the index is the primary key eventid of the meetupevent object;

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;    }}

4. Perform the batch update operation.

If the updated data volume is large, we recommend that you first update ElasticSearch indexes in batch mode on the Data Source Page.

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);

5. Summarize the use of NEST driver

Use the following code to connect to the NEST client:

var node = new Uri("http://myserver:9200");var settings = new ConnectionSettings(node);var client = new ElasticClient(settings);

Use the Index method of the client to update/Add a single document:

Client.Index(student);

Update/add multiple documents using the client's index.html function:

var list = new List<Student>();client.IndexMany<Student>(list);

To update documents in batches using the Bulk method of the client, you need to construct a BulkRequest parameter based on the object List:

client.Bulk(bulkRequest);

 

 

Reference:

NEST User Guide

Elasticsearch.net search getting started

ElasticSearch NEST notes

. Net ElasticSearch

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.