.Net?Api?中使用Elasticsearch存儲文檔的方法
什么是Elasticsearch?
Elasticsearch 是一個分布式、高擴展、高實時的搜索與數(shù)據(jù)分析引擎。它能很方便的使大量數(shù)據(jù)具有搜索、分析和探索的能力。充分利用Elasticsearch的水平伸縮性,能使數(shù)據(jù)在生產(chǎn)環(huán)境變得更有價值。Elasticsearch 的實現(xiàn)原理主要分為以下幾個步驟,首先用戶將數(shù)據(jù)提交到Elasticsearch 數(shù)據(jù)庫中,再通過分詞控制器去將對應(yīng)的語句分詞,將其權(quán)重和分詞結(jié)果一并存入數(shù)據(jù),當(dāng)用戶搜索數(shù)據(jù)時候,再根據(jù)權(quán)重將結(jié)果排名,打分,再將返回結(jié)果呈現(xiàn)給用戶。
總之這個數(shù)據(jù)庫可以很靈活的對你存入的數(shù)據(jù)進行分詞并查詢,可以靈活的處理字段內(nèi)容,篩選你想要的數(shù)據(jù),更重要的是這個數(shù)據(jù)庫是分布式的,可以減少應(yīng)為一個數(shù)據(jù)庫down掉而導(dǎo)致的數(shù)據(jù)丟失。
以下簡稱Elasticsearch為Es數(shù)據(jù)庫。前言 | Elasticsearch: 權(quán)威指南 | Elastic
用Nest使用Es數(shù)據(jù)庫
配置Nest
在C# 的環(huán)境中,有一個Es的官方拓展包Nest,可以讓我們方便快捷的使用上Es數(shù)據(jù)庫。首先在我們新建完項目后,需要在Nuget包管理中給項目安裝NEST包。
安裝完NEST包之后,需要新建一個Es的配置類EsConfig.cs,這里我們只使用最簡單的賬號,密碼和數(shù)據(jù)庫地址
/// <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);
}在配置對該接口的實現(xiàn)類ElasticsearchClient.cs,在這個實現(xiàn)類中我們使用了IOptions的依賴注入的形式來對配置文件進行配置,這種模式通常適用于API類型項目的配置。
我們也可以使用直接_EsConfig = Configuration.GetSection("EsConfig").Get<EsConfig>();的形式來讀取配置文件進行配置
/// <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è)置賬號密碼
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中對其進行注入。
services.Configure<EsConfig>(Configuration.GetSection("EsConfig"));操作數(shù)據(jù)庫
平時在我們操作數(shù)據(jù)庫之前,我們通常會有一個“建庫”、“建表”等操作,在Es中我們可以理解為創(chuàng)建索引基礎(chǔ)入門 | Elasticsearch: 權(quán)威指南 | Elastic。
由于Es數(shù)據(jù)庫目前還沒有很好的IDE去管理它,我們通常使用代碼來實現(xiàn)表的創(chuàng)建,所以先新建一個Es的拓展類來創(chuàng)建表ElasticClientExtension.cs
/// <summary>
/// ElasticClient 擴展類
/// </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;
}
}
}然后就是需要創(chuàng)建我們針對索引的方法了,我使用的是一個索引新建一個方法,新建一個ElaticSearchBase.cs,在這里我們假設(shè)要創(chuàng)建一個叫XXX的索引,首先我們要定義好一個叫XXX的類,我這里新建了一個主鍵和一個xml字段,用來存儲xml的數(shù)據(jù)。然后我在ElaticSearchBase.cs新建一個專屬于連接XXX索引的客戶端Client_XXX,如果數(shù)據(jù)庫中存在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ù)庫中存在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));
還有更多的查詢操作,可以查看官網(wǎng)內(nèi)容:結(jié)構(gòu)化搜索 | Elasticsearch: 權(quán)威指南 | Elastic
到此這篇關(guān)于.Net Api 之如何使用Elasticsearch存儲文檔的文章就介紹到這了,更多相關(guān).Net Api 使用Elasticsearch存儲文檔內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
WPF開發(fā)之利用DrawingVisual繪制高性能曲線圖
通過WPF實現(xiàn)大數(shù)據(jù)曲線圖時,如果用最基礎(chǔ)的Canvas來實現(xiàn),性能堪憂。所以本文將利用DrawingVisual繪制高性能曲線圖,感興趣的可以了解一下2022-02-02
ASP.NET使用AjaxPro實現(xiàn)前端跟后臺交互詳解
這篇文章主要為大家詳細介紹了ASP.NET使用AjaxPro實現(xiàn)前端跟后臺交互,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
詳解c# .net core 下的網(wǎng)絡(luò)請求
本篇文章主要介紹了詳解c# .net core 下的網(wǎng)絡(luò)請求,大致介紹下在.net core 下如何進行http請求,主要仍然是GET和POST方法,有興趣的可以了解下2017-05-05
在.NET程序崩潰時自動創(chuàng)建Dump的思路詳解
本文主要是介紹了如何在dotNet程序崩潰時自動創(chuàng)建Dump,Windows上的方法對于.NET Freamwork和.NET Core版本都適用,.NET Core全平臺版本的話需要注意環(huán)境變量支持的.NET版本,對.net程序崩潰自動創(chuàng)建Dump相關(guān)知識感興趣的朋友一起看看吧2022-11-11

