.Net Api 中使用Elasticsearch存儲文檔的方法

什麼是Elasticsearch?

Elasticsearch 是一個分佈式、高擴展、高實時的搜索與數據分析引擎。它能很方便的使大量數據具有搜索、分析和探索的能力。充分利用Elasticsearch的水平伸縮性,能使數據在生產環境變得更有價值。Elasticsearch 的實現原理主要分為以下幾個步驟,首先用戶將數據提交到Elasticsearch 數據庫中,再通過分詞控制器去將對應的語句分詞,將其權重和分詞結果一並存入數據,當用戶搜索數據時候,再根據權重將結果排名,打分,再將返回結果呈現給用戶。

總之這個數據庫可以很靈活的對你存入的數據進行分詞並查詢,可以靈活的處理字段內容,篩選你想要的數據,更重要的是這個數據庫是分佈式的,可以減少應為一個數據庫down掉而導致的數據丟失。

以下簡稱Elasticsearch為Es數據庫。前言 | Elasticsearch: 權威指南 | Elastic

用Nest使用Es數據庫

配置Nest

在C# 的環境中,有一個Es的官方拓展包Nest,可以讓我們方便快捷的使用上Es數據庫。首先在我們新建完項目後,需要在Nuget包管理中給項目安裝NEST包。

安裝完NEST包之後,需要新建一個Es的配置類EsConfig.cs,這裡我們隻使用最簡單的賬號,密碼和數據庫地址

 /// <summary>
    /// ES配置類
    /// </summary>
    public class EsConfig
    {
        /// <summary>
        /// 賬號
        /// </summary>
        public string username { get; set; }
        /// <summary>
        /// 密碼
        /// </summary>
        public string password { get; set; }
        /// <summary>
        /// ES地址
        /// </summary>
        public string url { get; set; }
    }

有瞭配置類之後,需要在程序啟動時,對Es進行配置。首先這裡先新建一個Es客戶端的接口類IElasticsearchClient.cs

 /// <summary>
    /// ES客戶端
    /// </summary>
    public interface IElasticsearchClient
    {
        /// <summary>
        /// 獲取ElasticClient
        /// </summary>
        /// <returns></returns>
        ElasticClient GetClient();
        /// <summary>
        /// 指定index獲取ElasticClient
        /// </summary>
        /// <param name="indexName"></param>
        /// <returns></returns>
        ElasticClient GetClient(string indexName);
    }

在配置對該接口的實現類ElasticsearchClient.cs,在這個實現類中我們使用瞭IOptions的依賴註入的形式來對配置文件進行配置,這種模式通常適用於API類型項目的配置。

我們也可以使用直接_EsConfig = Configuration.GetSection("EsConfig").Get<EsConfig>();的形式來讀取配置文件進行配置

/// <summary>
    /// ES客戶端
    /// </summary>
    public class ElasticsearchClient : IElasticsearchClient
    {
        public EsConfig _EsConfig;
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="esConfig"></param>
        public ElasticsearchClient(IOptions<EsConfig> esConfig)
        {
            _EsConfig = esConfig.Value;
        }
        /// <summary>
        /// 獲取elastic client
        /// </summary>
        /// <returns></returns>
        public ElasticClient GetClient()
        {
            if (_EsConfig == null || _EsConfig.url == null || _EsConfig.url == "")
            {
                throw new Exception("urls can not be null");
            }
            return GetClient(_EsConfig.url, "");
        }
        /// <summary>
        /// 指定index獲取ElasticClient
        /// </summary>
        /// <param name="indexName"></param>
        /// <returns></returns>
        public ElasticClient GetClient(string indexName)
        {
            if (_EsConfig == null || _EsConfig.url == null || _EsConfig.url == "")
            {
                throw new Exception("urls can not be null");
            }
            return GetClient(_EsConfig.url, indexName);
        }
        /// <summary>
        /// 根據url獲取ElasticClient
        /// </summary>
        /// <param name="url"></param>
        /// <param name="defaultIndex"></param>
        /// <returns></returns>
        private ElasticClient GetClient(string url, string defaultIndex = "")
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new Exception("urls can not be null");
            }
            var uri = new Uri(url);
            var connectionSetting = new ConnectionSettings(uri);
            if (!string.IsNullOrWhiteSpace(url))
            {
                connectionSetting.DefaultIndex(defaultIndex);
            }
            connectionSetting.BasicAuthentication(_EsConfig.username, _EsConfig.password); //設置賬號密碼
            return new ElasticClient(connectionSetting);
        }
        /// <summary>
        /// 根據urls獲取ElasticClient
        /// </summary>
        /// <param name="urls"></param>
        /// <param name="defaultIndex"></param>
        /// <returns></returns>
        private ElasticClient GetClient(string[] urls, string defaultIndex = "")
        {
            if (urls == null || urls.Length < 1)
            {
                throw new Exception("urls can not be null");
            }
            var uris = urls.Select(p => new Uri(p)).ToArray();
            var connectionPool = new SniffingConnectionPool(uris);
            var connectionSetting = new ConnectionSettings(connectionPool);
            if (!string.IsNullOrWhiteSpace(defaultIndex))
            {
                connectionSetting.DefaultIndex(defaultIndex);
            }
            return new ElasticClient(connectionSetting);
        }
    }

既然是依賴註入別忘瞭在Startup.cs中對其進行註入。

services.Configure<EsConfig>(Configuration.GetSection("EsConfig"));

操作數據庫

平時在我們操作數據庫之前,我們通常會有一個“建庫”、“建表”等操作,在Es中我們可以理解為創建索引基礎入門 | Elasticsearch: 權威指南 | Elastic。

由於Es數據庫目前還沒有很好的IDE去管理它,我們通常使用代碼來實現表的創建,所以先新建一個Es的拓展類來創建表ElasticClientExtension.cs

 /// <summary>
    /// ElasticClient 擴展類
    /// </summary>
    public static class ElasticClientExtension
    {
        /// <summary>
        /// 創建索引
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="elasticClient"></param>
        /// <param name="indexName"></param>
        /// <param name="numberOfShards"></param>
        /// <param name="numberOfReplicas"></param>
        /// <returns></returns>
        public static bool CreateIndex<T>(this ElasticClient elasticClient, string indexName = "", int numberOfShards = 10, int numberOfReplicas = 1) where T : class
        {

            if (string.IsNullOrWhiteSpace(indexName))
            {
                indexName = typeof(T).Name;
            }

            if (elasticClient.Indices.Exists(indexName).Exists)
            {
                return false;
            }
            else
            {
                var indexState = new IndexState()
                {
                    Settings = new IndexSettings()
                    {
                        NumberOfReplicas = numberOfReplicas,
                        NumberOfShards = numberOfShards,
                    },
                };
                var response = elasticClient.Indices.Create(indexName, p => p.InitializeUsing(indexState).Map<T>(p => p.AutoMap()));
                return response.Acknowledged;
            }
        }
    }

然後就是需要創建我們針對索引的方法瞭,我使用的是一個索引新建一個方法,新建一個ElaticSearchBase.cs,在這裡我們假設要創建一個叫XXX的索引,首先我們要定義好一個叫XXX的類,我這裡新建瞭一個主鍵和一個xml字段,用來存儲xml的數據。然後我在ElaticSearchBase.cs新建一個專屬於連接XXX索引的客戶端Client_XXX,如果數據庫中存在xxx則直接連接,如果不存在則新建後連接。

  public class XXX
    {
        public int xid { get; set; }
        [Text(Name = "xml")]
        public string xml { get; set; }
    }
  public class ElaticSearchBase
    {

        private IElasticsearchClient _client;
        public ElaticSearchBase(IElasticsearchClient client)
        {
            _client = client;
        }
        /// <summary>
        /// XXX文檔索引
        /// </summary>
        public ElasticClient Client_XXX => GetXXX();

        private ElasticClient GetXXX()
        {
	    //如果數據庫中存在xxx則直接連接,如果不存在則新建後連接
            var client = _client.GetClient("XXX");
            if (!client.Indices.Exists("XXX").Exists)
            {
                client.CreateIndex<XXX>("XXX");
            }
            return client;
        }
    }

接下來我們到瞭實操部分:

新增

private ElaticSearchBase _es = new ElaticSearchBase(_client);
//實例化對象
var xxx1 = new XXX(){tempid = 1,xml = "xmlstring"};
//存儲xxx1
var res =_es.Client_XXX.IndexDocument(xxx1);
//獲得Es主鍵
var esid = res.Id;

查詢

var res = _es.Client_XXX.Get<XXX>(esid);

刪除

var res = _es.Client_XXX.Delete<XXX>(esid)

修改

//實例化對象
var xxx2 = new XXX(){tempid = 2,xml = "xmlstring2"};
var upRes= _es.Client_XXX.Update<XXX, object>(ex.xmlid, upt => upt.Doc(xxx2));

還有更多的查詢操作,可以查看官網內容:結構化搜索 | Elasticsearch: 權威指南 | Elastic

到此這篇關於.Net Api 之如何使用Elasticsearch存儲文檔的文章就介紹到這瞭,更多相關.Net Api 使用Elasticsearch存儲文檔內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: