首页 > 其他分享 >我的网站集成ElasticSearch初体验

我的网站集成ElasticSearch初体验

时间:2024-09-22 12:12:45浏览次数:1  
标签:集成 初体验 string List Field ElasticSearch using new public

   最近,我给我的网站(https://www.xiandanplay.com/)尝试集成了一下es来实现我的一个搜索功能,因为这个是我第一次了解运用elastic,所以如果有不对的地方,大家可以指出来,话不多说,先看看我的一个大致流程

      这里我采用的sdk的版本是Elastic.Clients.Elasticsearch, Version=8.0.0.0,官方的网址Installation | Elasticsearch .NET Client [8.0] | Elastic

      我的es最开始打算和我的应用程序一起部署到ubuntu上面,结果最后安装kibana的时候,各种问题,虽好无奈,只好和我的SqlServer一起安装到windows上面,对于一个2G内容的服务器来说,属实有点遭罪了。

1、配置es

 在es里面,我开启了密码认证。下面是我的配置

"Search": {
    "IsEnable": "true",
    "Uri": "http://127.0.0.1:9200/",
    "User": "123",
    "Password": "123"
  }
然后新增一个程序集

然后再ElasticsearchClient里面去写一个构造函数去配置es

using Core.Common;
using Core.CPlatform;
using Core.SearchEngine.Attr;
using Elastic.Clients.Elasticsearch;
using Elastic.Clients.Elasticsearch.IndexManagement;
using Elastic.Transport;

namespace Core.SearchEngine.Client
{
    public class ElasticSearchClient : IElasticSearchClient
    {
        private ElasticsearchClient elasticsearchClient;
        public ElasticSearchClient()
        {
            string uri = ConfigureProvider.configuration.GetSection("Search:Uri").Value;
            string username = ConfigureProvider.configuration.GetSection("Search:User").Value;
            string password = ConfigureProvider.configuration.GetSection("Search:Password").Value;
            var settings = new ElasticsearchClientSettings(new Uri(uri))
                          .Authentication(new BasicAuthentication(username, password)).DisableDirectStreaming();
            elasticsearchClient = new ElasticsearchClient(settings);
        }
        public ElasticsearchClient GetClient()
        {
            return elasticsearchClient;
        }
    }
}

   然后,我们看skd的官网有这个这个提示

 客户端应用程序应创建一个 该实例,该实例在整个应用程序中用于整个应用程序 辈子。在内部,客户端管理和维护与节点的 HTTP 连接, 重复使用它们以优化性能。如果您使用依赖项注入 容器中,客户端实例应注册到 单例生存期

所以我直接给它来一个AddSingleton

using Core.SearchEngine.Client;
using Microsoft.Extensions.DependencyInjection;

namespace Core.SearchEngine
{
    public static class ConfigureSearchEngine
    {
        public static void AddSearchEngine(this IServiceCollection services)
        {
            services.AddSingleton<IElasticSearchClient, ElasticSearchClient>();
        }
    }
}

2、提交文章并且同步到es

 然后就是同步文章到es了,我是先写入数据库,再同步到rabbitmq,通过事件总线(基于事件总线EventBus实现邮件推送功能)写入到es

先定义一个es模型

using Core.SearchEngine.Attr;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XianDan.Model.BizEnum;

namespace XianDan.Domain.Article
{
    [ElasticsearchIndex(IndexName ="t_article")]//自定义的特性,sdk并不包含这个特性
    public class Article_ES
    {
        public long Id { get; set; }
        /// <summary>
        /// 作者
        /// </summary>
        public string Author { get; set; }
        /// <summary>
        /// 标题                                                                               
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 标签
        /// </summary>
        public string Tag { get; set; }
        /// <summary>
        /// 简介                                                                              
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string ArticleContent { get; set; }
        /// <summary>
        /// 专栏
        /// </summary>
        public long ArticleCategoryId { get; set; }
        /// <summary>
        /// 是否原创
        /// </summary>
        public bool? IsOriginal { get; set; }
        /// <summary>
        /// 评论数
        /// </summary>
        public int? CommentCount { get; set; }
        /// <summary>
        /// 点赞数
        /// </summary>
        public int? PraiseCount { get; set; }
        /// <summary>
        /// 浏览次数
        /// </summary>
        public int? BrowserCount { get; set; }
        /// <summary>
        /// 收藏数量
        /// </summary>
        public int? CollectCount { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }
    }
}

然后创建索引

 string index = esArticleClient.GetIndexName(typeof(Article_ES));
            await esArticleClient.GetClient().Indices.CreateAsync<Article_ES>(index, s =>
            s.Mappings(
                x => x.Properties(
                    t => t.LongNumber(l => l.Id)
                         .Text(l=>l.Title,z=>z.Analyzer(ik_max_word))
                         .Keyword(l=>l.Author)
                         .Text(l=>l.Tag,z=>z.Analyzer(ik_max_word))
                         .Text(l=>l.Description,z=>z.Analyzer(ik_max_word))
                         .Text(l=>l.ArticleContent,z=>z.Analyzer(ik_max_word))
                         .LongNumber(l=>l.ArticleCategoryId)
                         .Boolean(l=>l.IsOriginal)
                         .IntegerNumber(l=>l.BrowserCount)
                         .IntegerNumber(l=>l.PraiseCount)
                         .IntegerNumber(l=>l.PraiseCount)
                         .IntegerNumber(l=>l.CollectCount)
                         .IntegerNumber(l=>l.CommentCount)
                         .Date(l=>l.CreateTime)
                    )
                )
            );

然后每次增删改文章的时候写入到mq,例如

 private async Task SendToMq(Article article, Operation operation)
        {
            ArticleEventData articleEventData = new ArticleEventData();
            articleEventData.Operation = operation;
            articleEventData.Article_ES = MapperUtil.Map<Article, Article_ES>(article);
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.Id = CreateEntityId();
            taskRecord.TaskType = TaskRecordType.MQ;
            taskRecord.TaskName = "发送文章";
            taskRecord.TaskStartTime = DateTime.Now;
            taskRecord.TaskStatu = (int)MqMessageStatu.New;
            articleEventData.Unique = taskRecord.Id.ToString();
            taskRecord.TaskValue = JsonConvert.SerializeObject(articleEventData);
            await unitOfWork.GetRepository<TaskRecord>().InsertAsync(taskRecord);
            await unitOfWork.CommitAsync();
            try
            {
                eventBus.Publish(GetMqExchangeName(), ExchangeType.Direct, BizKey.ArticleQueueName, articleEventData);
            }
            catch (Exception ex)
            {
                var taskRecordRepository = unitOfWork.GetRepository<TaskRecord>();
                TaskRecord update = await taskRecordRepository.SelectByIdAsync(taskRecord.Id);
                update.TaskStatu = (int)MqMessageStatu.Fail;
                update.LastUpdateTime = DateTime.Now;
                update.TaskResult = "发送失败";
                update.AdditionalData = ex.Message;
                await taskRecordRepository.UpdateAsync(update);
                await unitOfWork.CommitAsync();
            }

        }

mq订阅之后写入es,具体的增删改的方法就不写了吧

3、开始查询es

  等待写入文章之后,开始查询文章,这里sdk提供的查询的方法比较复杂,全都是通过lmbda一个个链式去拼接的,但是我又没有找到更好的方法,所以就先这样吧

   先创建一个集合存放查询的表达式

List<Action<QueryDescriptor<Article_ES>>> querys = new List<Action<QueryDescriptor<Article_ES>>>();

   然后定义一个几个需要查询的字段

   我这里使用MultiMatch来实现多个字段匹配同一个查询条件,并且指定使用ik_smart分词

Field[] fields =
                {
                    new Field("title"),
                    new Field("tag"),
                    new Field("articleContent"),
                    new Field("description")
                };
 querys.Add(s => s.MultiMatch(y => y.Fields(Fields.FromFields(fields)).Analyzer(ik_smart).Query(keyword).Type(TextQueryType.MostFields)));

定义查询结果高亮,给查询出来的匹配到的分词的字段添加标签,同时前端需要对这个样式处理,

:deep(.search-words) em {     color: #ee0f29;     font-style: initial; }
 Dictionary<Field, HighlightField> highlightFields = new Dictionary<Field, HighlightField>();
            highlightFields.Add(new Field("title"), new HighlightField()
            {
                PreTags = new List<string> { "<em>" },
                PostTags = new List<string> { "</em>" },
            });
            highlightFields.Add(new Field("description"), new HighlightField()
            {
                PreTags = new List<string> { "<em>" },
                PostTags = new List<string> { "</em>" },
            });
            Highlight highlight = new Highlight()
            {
                Fields = highlightFields
            };

为了提高查询的效率,我只查部分的字段

 SourceFilter sourceFilter = new SourceFilter();
            sourceFilter.Includes = Fields.FromFields(new Field[] { "title", "id", "author", "description", "createTime", "browserCount", "commentCount" });
            SourceConfig sourceConfig = new SourceConfig(sourceFilter);
            Action<SearchRequestDescriptor<Article_ES>> configureRequest = s => s.Index(index)
            .From((homeArticleCondition.CurrentPage - 1) * homeArticleCondition.PageSize)
            .Size(homeArticleCondition.PageSize)
            .Query(x => x.Bool(y => y.Must(querys.ToArray())))
            .Source(sourceConfig)
             .Sort(y => y.Field(ht => ht.CreateTime, new FieldSort() { Order=SortOrder.Desc}))

获取查询的分词结果

 var analyzeIndexRequest = new AnalyzeIndexRequest
            {
                Text = new string[] { keyword },
                Analyzer = analyzer
            };
            var analyzeResponse = await elasticsearchClient.Indices.AnalyzeAsync(analyzeIndexRequest);
            if (analyzeResponse.Tokens == null)
                return new string[0];
            return analyzeResponse.Tokens.Select(s => s.Token).ToArray();

到此,这个就是大致的查询结果,完整的如下

 public async Task<Core.SearchEngine.Response.SearchResponse<Article_ES>> SelectArticle(HomeArticleCondition homeArticleCondition)
        {
            string keyword = homeArticleCondition.Keyword.Trim();
            bool isNumber = Regex.IsMatch(keyword, RegexPattern.IsNumberPattern);
            List<Action<QueryDescriptor<Article_ES>>> querys = new List<Action<QueryDescriptor<Article_ES>>>();
            if (isNumber)
            {
                querys.Add(s => s.Bool(x => x.Should(
                    should => should.Term(f => f.Field(z => z.Title).Value(keyword))
                    , should => should.Term(f => f.Field(z => z.Tag).Value(keyword))
                    , should => should.Term(f => f.Field(z => z.ArticleContent).Value(keyword))
                    )));
            }
            else
            {
                Field[] fields =
                {
                    new Field("title"),
                    new Field("tag"),
                    new Field("articleContent"),
                    new Field("description")
                };
                querys.Add(s => s.MultiMatch(y => y.Fields(Fields.FromFields(fields)).Analyzer(ik_smart).Query(keyword).Type(TextQueryType.MostFields)));
            }
            if (homeArticleCondition.ArticleCategoryId.HasValue)
            {
                querys.Add(s => s.Term(t => t.Field(f => f.ArticleCategoryId).Value(FieldValue.Long(homeArticleCondition.ArticleCategoryId.Value))));
            }
            string index = esArticleClient.GetIndexName(typeof(Article_ES));
            Dictionary<Field, HighlightField> highlightFields = new Dictionary<Field, HighlightField>();
            highlightFields.Add(new Field("title"), new HighlightField()
            {
                PreTags = new List<string> { "<em>" },
                PostTags = new List<string> { "</em>" },
            });
            highlightFields.Add(new Field("description"), new HighlightField()
            {
                PreTags = new List<string> { "<em>" },
                PostTags = new List<string> { "</em>" },
            });
            Highlight highlight = new Highlight()
            {
                Fields = highlightFields
            };
            SourceFilter sourceFilter = new SourceFilter();
            sourceFilter.Includes = Fields.FromFields(new Field[] { "title", "id", "author", "description", "createTime", "browserCount", "commentCount" });
            SourceConfig sourceConfig = new SourceConfig(sourceFilter);
            Action<SearchRequestDescriptor<Article_ES>> configureRequest = s => s.Index(index)
            .From((homeArticleCondition.CurrentPage - 1) * homeArticleCondition.PageSize)
            .Size(homeArticleCondition.PageSize)
            .Query(x => x.Bool(y => y.Must(querys.ToArray())))
            .Source(sourceConfig)
             .Sort(y => y.Field(ht => ht.CreateTime, new FieldSort() { Order=SortOrder.Desc})).Highlight(highlight);
            var resp = await esArticleClient.GetClient().SearchAsync<Article_ES>(configureRequest);
            foreach (var item in resp.Hits)
            {
                if (item.Highlight == null)
                    continue;
                foreach (var dict in item.Highlight)
                {
                    switch (dict.Key)
                    {
                        case "title":
                            item.Source.Title = string.Join("...", dict.Value);
                            break;
                        case "description":
                            item.Source.Description = string.Join("...", dict.Value);
                            break;

                    }
                }
            }
            string[] analyzeWords = await esArticleClient.AnalyzeAsync(homeArticleCondition.Keyword);
            List<Article_ES> articles = resp.Documents.ToList();
            return new Core.SearchEngine.Response.SearchResponse<Article_ES>(articles, analyzeWords);
        }

4、演示效果    

搞完之后,发布部署,看看效果,分词这里要想做的像百度那样,估计目前来看非常有难度的

   那么这里我也向大家求教一下,如何使用SearchRequest封装多个查询条件,如下

SearchRequest searchRequest = new SearchRequest();
 searchRequest.From = 0;
searchRequest.Size = 10;
  searchRequest.Query=多个查询条件

因为我觉得这样代码读起来比lambda可读性高些,能更好的动态封装。

 

标签:集成,初体验,string,List,Field,ElasticSearch,using,new,public
From: https://www.cnblogs.com/MrHanBlog/p/18425152

相关文章

  • 在 Elasticsearch 中段(Segment)的组成部分
    在Elasticsearch中,一个索引由多个**分片(Shard)**组成,而每个分片又由多个**段(Segment)**构成。段是索引的最小搜索单元,是不可变的,一旦创建,其内容就不会再改变。以下是段(Segment)的组成部分:1.**倒排索引(InvertedIndex)**:这是Elasticsearch用来实现快速搜索的核心数据结构。它......
  • QT QML模块的持续集成
    QTQML模块的持续集成使用AI技术辅助生成QT界面美化视频课程QT性能优化视频课程QT原理与源码分析视频课程QTQMLC++扩展开发视频课程免费QT视频课程您可以看免费1000+个QT技术视频免费QT视频课程QT统计图和QT数据可视化视频免费看免费QT视频课程QT性能优化视频免费看......
  • 【Ambari自定义组件集成】Bigtop编译大数据组件,看这一篇就够了
    快捷导航在正式内容之前,通过下方导航,大家可以快速找到相关资源:快捷导航链接地址备注相关文档-ambari+bigtop自定义组件集成https://blog.csdn.net/TTBIGDATA/article/details/142150086CSDN地址编译、开发、部署、集成解决方案https://t.zsxq.com/0PVcI知识星球源代码-Ambar......
  • Java中的多数据源管理:如何在单个应用中集成多数据库
    Java中的多数据源管理:如何在单个应用中集成多数据库大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!在现代软件架构中,应用往往需要访问多个数据库以支持不同的业务需求。本文将介绍如何在Java应用中实现多数据源管理,包括配置、使用和切换数据源的最佳......
  • Elasticsearch 应用实战:从基础到高级实践
    引言Elasticsearch是一个开源的实时分布式搜索和分析引擎,基于ApacheLucene构建,广泛应用于日志分析、全文检索、数据可视化等场景。本文将探讨Elasticsearch的基本概念、安装与配置、以及实际应用案例,以帮助开发者更好地理解和利用这一强大的搜索引擎。更多内容,请查阅1.......
  • 【Elasticsearch系列十七】索引 index
    ......
  • 【服务集成】最新版 | 阿里云OSS对象存储服务使用教程(包含OSS工具类优化、自定义阿里
    文章目录一、阿里云OSS对象存储服务介绍二、服务开通与使用准备1、准备工作2、开通OSS云服务(新用户免费使用三个月)3、创建存储空间bucket4、创建并保存Accesskey5、配置访问凭证AK&SK(系统环境变量)三、阿里云OSS使用步骤1、导入依赖坐标2、文件上传Demo快速入门3、阿里......
  • Docker 与 GitHub:完美结合实现容器化部署与持续集成
    Docker与GitHub:完美结合实现容器化部署与持续集成使用Docker和GitHub,开发者可以将代码构建、测试和部署流程自动化,从而提高开发效率,确保应用程序的一致性与可靠性。本文将介绍如何使用Docker和GitHubActions实现容器化部署与持续集成。目录概述Docker基础知识Docker镜......
  • ElasticSearch的搜索方式
    目录目录前言数据准备文档搜索一、查询所有文档二、全文检索(1)全文检索(2)自动纠错三、范围搜索四、短语检索五、单词/词组搜索六、复合搜索前言数据准备PUT/students{"mappings":{"properties":{"id":{"type":"integer",......
  • 基于UKF(无迹卡尔曼滤波)的SINS/GPS集成导航仿真程序【需要PSINS工具箱支持】
    文章目录主要特点内容包括运行截图基于UKF(无迹卡尔曼滤波)的SINS/GPS集成导航仿真程序(需要基于PSINS工具箱,工具箱是开源的,如果需要,可以确认收货后找我要链接)。该程序能够高效地模拟导航数据,并提供详细的滤波结果及误差分析,适用于科研和工程项目。带详细的中文注释主要......