1. 程式人生 > 實用技巧 >.net core 如何向elasticsearch中建立索引,插入資料。

.net core 如何向elasticsearch中建立索引,插入資料。

首先我們要建一個webapi工程,然後下載兩個外掛:

1,Nest 2,Elasticsearch.Net

下載後,下面就上程式碼了,首先是elasticsearchHelp幫助類

using Elasticsearch.Net;
using Nest;
using System;
namespace ESAPI.Common
{
    public static class ElasticSearchHelper
    {
public static readonly string url = "http://ip:9200/";//這個是elasticsearch遠端訪問ip
public static void insert(object t,string index) { //設定連線字串,DefaultIndex中的表名要小寫 var settings = new ConnectionSettings(new Uri(url)).DefaultIndex(index); var client = new ElasticClient(settings); var doc = t; //通過 IndexDocument() 方法插入資料
var ndexResponse = client.IndexDocument(doc); } /// <summary> /// 單點連結到ElasticSearch /// </summary> /// <param name="url">ElasticSearch的ip地址</param> /// <returns></returns> public static ElasticClient OneConnectES(string
url) { var node = new Uri(url); var settings = new ConnectionSettings(node); var client = new ElasticClient(settings); return client; } /// <summary> /// 指定多個節點使用連線池連結到Elasticsearch叢集 /// </summary> /// <param name="serverurl">連結ip陣列</param> /// <returns></returns> public static ElasticClient ManyConnectES(string[] serverurl) { Uri[] nodes = new Uri[serverurl.Length]; for (int i = 0; i < serverurl.Length; i++) { nodes[i] = new Uri(serverurl[i]); } var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool); var client = new ElasticClient(settings); return client; } /// <summary> /// 建立索引 /// </summary> /// <param name="elasticClient"></param> public static CreateIndexResponse CreateIndex(this IElasticClient elasticClient, string indexName, int numberOfReplicas = 1, int numberOfShards = 5) { IIndexState indexState = new IndexState { Settings = new IndexSettings { NumberOfReplicas = numberOfReplicas, // [副本數量] NumberOfShards = numberOfShards } }; Func<CreateIndexDescriptor, ICreateIndexRequest> func = x => x.InitializeUsing(indexState).Map(m => m.AutoMap()); CreateIndexResponse response = elasticClient.Indices.Create(indexName, func); return response; } } }

控制器程式碼:

using System;
using ESAPI.Common;
using Microsoft.AspNetCore.Mvc;
namespace ESAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
         /// <summary>
         /// 刪除地址
         /// </summary>
         /// <param name="id"></param>
         [HttpGet("InsertLog")]
         public void InsertLog()
         {
//插入200條資料
for (int i = 0; i < 200; i++) { var d = new { Time = DateTime.Now, Num = 5, Name = "12313", info = "hello world!" }; ElasticSearchHelper.insert(d, "demo"); } } } }

執行程式:

檢視elasticsearch視覺化介面:

很顯然,插入成功了!既然是ELK,後續我還會對logstash,Kibana的安裝和使用也進行詳細的介紹,下一篇,會詳細介紹logstash的安裝和使用!