.Net Api 之如何使用Elasticsearch儲存文件

野菊花發表於2022-01-25

.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

相關文章