欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.Net?Api?中使用Elasticsearch存儲(chǔ)文檔的方法

 更新時(shí)間:2022年01月25日 11:49:14   作者:野菊花  
Elasticsearch 是一個(gè)分布式、高擴(kuò)展、高實(shí)時(shí)的搜索與數(shù)據(jù)分析引擎,在C# 的環(huán)境中,有一個(gè)Es的官方拓展包Nest,可以讓我們方便快捷的使用上Es數(shù)據(jù)庫(kù),本文重點(diǎn)給大家介紹.Net?Api?中使用Elasticsearch存儲(chǔ)文檔的方法,感興趣的朋友一起看看吧

什么是Elasticsearch?

Elasticsearch 是一個(gè)分布式、高擴(kuò)展、高實(shí)時(shí)的搜索與數(shù)據(jù)分析引擎。它能很方便的使大量數(shù)據(jù)具有搜索、分析和探索的能力。充分利用Elasticsearch的水平伸縮性,能使數(shù)據(jù)在生產(chǎn)環(huán)境變得更有價(jià)值。Elasticsearch 的實(shí)現(xiàn)原理主要分為以下幾個(gè)步驟,首先用戶將數(shù)據(jù)提交到Elasticsearch 數(shù)據(jù)庫(kù)中,再通過分詞控制器去將對(duì)應(yīng)的語(yǔ)句分詞,將其權(quán)重和分詞結(jié)果一并存入數(shù)據(jù),當(dāng)用戶搜索數(shù)據(jù)時(shí)候,再根據(jù)權(quán)重將結(jié)果排名,打分,再將返回結(jié)果呈現(xiàn)給用戶。

總之這個(gè)數(shù)據(jù)庫(kù)可以很靈活的對(duì)你存入的數(shù)據(jù)進(jìn)行分詞并查詢,可以靈活的處理字段內(nèi)容,篩選你想要的數(shù)據(jù),更重要的是這個(gè)數(shù)據(jù)庫(kù)是分布式的,可以減少應(yīng)為一個(gè)數(shù)據(jù)庫(kù)down掉而導(dǎo)致的數(shù)據(jù)丟失。

以下簡(jiǎn)稱Elasticsearch為Es數(shù)據(jù)庫(kù)。前言 | Elasticsearch: 權(quán)威指南 | Elastic

用Nest使用Es數(shù)據(jù)庫(kù)

配置Nest

在C# 的環(huán)境中,有一個(gè)Es的官方拓展包Nest,可以讓我們方便快捷的使用上Es數(shù)據(jù)庫(kù)。首先在我們新建完項(xiàng)目后,需要在Nuget包管理中給項(xiàng)目安裝NEST包。

安裝完NEST包之后,需要新建一個(gè)Es的配置類EsConfig.cs,這里我們只使用最簡(jiǎn)單的賬號(hào),密碼和數(shù)據(jù)庫(kù)地址

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

有了配置類之后,需要在程序啟動(dòng)時(shí),對(duì)Es進(jìn)行配置。首先這里先新建一個(gè)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);
    }

在配置對(duì)該接口的實(shí)現(xiàn)類ElasticsearchClient.cs,在這個(gè)實(shí)現(xiàn)類中我們使用了IOptions的依賴注入的形式來(lái)對(duì)配置文件進(jìn)行配置,這種模式通常適用于API類型項(xiàng)目的配置。

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

/// <summary>
    /// ES客戶端
    /// </summary>
    public class ElasticsearchClient : IElasticsearchClient
    {
        public EsConfig _EsConfig;
        /// <summary>
        /// 構(gòu)造函數(shù)
        /// </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>
        /// 根據(jù)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); //設(shè)置賬號(hào)密碼
            return new ElasticClient(connectionSetting);
        }
        /// <summary>
        /// 根據(jù)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中對(duì)其進(jìn)行注入。

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

操作數(shù)據(jù)庫(kù)

平時(shí)在我們操作數(shù)據(jù)庫(kù)之前,我們通常會(huì)有一個(gè)“建庫(kù)”、“建表”等操作,在Es中我們可以理解為創(chuàng)建索引基礎(chǔ)入門 | Elasticsearch: 權(quán)威指南 | Elastic。

由于Es數(shù)據(jù)庫(kù)目前還沒有很好的IDE去管理它,我們通常使用代碼來(lái)實(shí)現(xiàn)表的創(chuàng)建,所以先新建一個(gè)Es的拓展類來(lái)創(chuàng)建表ElasticClientExtension.cs

 /// <summary>
    /// ElasticClient 擴(kuò)展類
    /// </summary>
    public static class ElasticClientExtension
    {
        /// <summary>
        /// 創(chuàng)建索引
        /// </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;
            }
        }
    }

然后就是需要?jiǎng)?chuàng)建我們針對(duì)索引的方法了,我使用的是一個(gè)索引新建一個(gè)方法,新建一個(gè)ElaticSearchBase.cs,在這里我們假設(shè)要?jiǎng)?chuàng)建一個(gè)叫XXX的索引,首先我們要定義好一個(gè)叫XXX的類,我這里新建了一個(gè)主鍵和一個(gè)xml字段,用來(lái)存儲(chǔ)xml的數(shù)據(jù)。然后我在ElaticSearchBase.cs新建一個(gè)專屬于連接XXX索引的客戶端Client_XXX,如果數(shù)據(jù)庫(kù)中存在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()
        {
	    //如果數(shù)據(jù)庫(kù)中存在xxx則直接連接,如果不存在則新建后連接
            var client = _client.GetClient("XXX");
            if (!client.Indices.Exists("XXX").Exists)
            {
                client.CreateIndex<XXX>("XXX");
            }
            return client;
        }
    }

接下來(lái)我們到了實(shí)操部分:

新增

private ElaticSearchBase _es = new ElaticSearchBase(_client);
//實(shí)例化對(duì)象
var xxx1 = new XXX(){tempid = 1,xml = "xmlstring"};
//存儲(chǔ)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)

修改

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

還有更多的查詢操作,可以查看官網(wǎng)內(nèi)容:結(jié)構(gòu)化搜索 | Elasticsearch: 權(quán)威指南 | Elastic

到此這篇關(guān)于.Net Api 之如何使用Elasticsearch存儲(chǔ)文檔的文章就介紹到這了,更多相關(guān).Net Api 使用Elasticsearch存儲(chǔ)文檔內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論