全文检索这个系列在几前年写过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相关
感谢各位的阅读!
本文转自博客园张占岭(仓储大叔)的博客,原文链接:全文检索~solr的使用,如需转载请自行联系原博主。