全文檢索這個系列在幾前年寫過lucene的文章,而現在看來它确實已經老了,它的兒子孫子都出來了,已經成為現在檢索行列的主流,像solr,elasticsearch等,今天我們主要來看一個solr在aspnetcore裡的使用,也就是增删改查之類的,比較容易!
nuget包:solrnet
注入方式:全局單例注入
使用方式:構造方法注入
solr管理系統:它有自己的ui界面
solr裡core:類似于關系型資料庫裡的表,mongodb裡的集合
一 solr管理系統

services.AddSolrNet(o =>
{
o.ServerUrl = "http://192.168.200.214:8081/solr/system_companysubject";
o.UserName = "sa";
o.Password = "sa";
});
#region Private Fields
private ICache _cache;
private RepositoryConfig _config;
private HttpClient _httpClient = new HttpClient();
private ILogger _logger;
private IProducer _producer;
private IRepository<userinfo> _repository;
private ISolrOperations<System_CompanySubject> _solrOperations;
#endregion Private Fields
#region Public Constructors
public ValuesController(
IRepository<userinfo> repository,
IProducer producer,
ILogger logger,
ISolrOperations<System_CompanySubject> solrOperations,
RepositoryConfig config,
ICache cache)
{
_cache = cache;
_config = config;
_solrOperations = solrOperations;
_logger = logger;
_producer = producer;
_repository = repository;
_httpClient.Timeout = new TimeSpan(0, 0, 10);
_httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
}
#endregion Public Constructors
solr實作的增删改查,很是簡單
#region solr相關
[Route("~/Solr")]
public IEnumerable<string> Solr(string companyId, string subjectName)
{
List<ISolrQuery> query = new List<ISolrQuery>();
if (!string.IsNullOrWhiteSpace(companyId))
query.Add(new SolrQueryByField("companyId", companyId));
if (!string.IsNullOrWhiteSpace(subjectName))
query.Add(new SolrQueryByField("subjectName", subjectName));
var subjects = _solrOperations.Query(new SolrMultipleCriteriaQuery(query, Operator.AND), new QueryOptions
{
StartOrCursor = new StartOrCursor.Start(0),
// Rows = 1
});
if (subjects != null && subjects.Count > 0)
{
foreach (var item in subjects)
{
yield return $"company:{item.CompanyId},subjectName:{item.SubjectName}";
}
}
}
[Route("~/SolrAdd")]
public string SolrAdd()
{
_solrOperations.Add(new System_CompanySubject
{
Id = "101",
CompanyId = 1,
SubjectName = "測試現金",
SubjectNo = "1001",
});
_solrOperations.Add(new System_CompanySubject
{
Id = "100",
CompanyId = 1,
SubjectName = "測試結算",
SubjectNo = "1002",
});
// _solrOperations.Commit();//重建立立索引
return "add ok";
}
[Route("~/SolrDel")]
public string SolrDel(string id)
{
var query = new SolrQueryByField("id", id);
_solrOperations.Delete(query);
return "del ok";
}
#endregion solr相關
感謝各位的閱讀!
作者:倉儲大叔,張占嶺,
榮譽:微軟MVP
QQ:853066980
支付寶掃一掃,為大叔打賞!