Meilisearch ASP.Net Core API 功能demo

ops/2025/1/13 3:59:09/
  1. 安装
MeiliSearch                 0.15.5   0.15.5
  1. demo code
using Meilisearch;
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;namespace MeiliSearchAPI
{public class MeilisearchHelper{public MeilisearchHelper(){DefaultClient = new MeilisearchClient(MeilisearchAddress(), ApiKey);var httpClient = new HttpClient(new MeilisearchMessageHandler(new HttpClientHandler())) { BaseAddress = new Uri(MeilisearchAddress()) };ClientWithCustomHttpClient = new MeilisearchClient(httpClient, ApiKey);}private const string ApiKey = "ellisniubitesthahaha";private static readonly string BasePath = Path.Combine(Directory.GetCurrentDirectory(), "Datasets");public static readonly string SmallMoviesJsonPath = Path.Combine(BasePath, "small_movies.json");public virtual string MeilisearchAddress(){return "http://192.168.214.133:31170";}public MeilisearchClient DefaultClient { get; private set; }public MeilisearchClient ClientWithCustomHttpClient { get; private set; }/// <summary>/// 从json文件插入document/// </summary>/// <returns></returns>public async Task InitIndexWithValue(string indexName){var index = DefaultClient.Index(indexName);var jsonDocuments = await File.ReadAllTextAsync(SmallMoviesJsonPath);var task = await index.AddDocumentsJsonAsync(jsonDocuments);await index.WaitForTaskAsync(task.TaskUid);}/// <summary>/// 根据类插入document/// </summary>/// <param name="datasetSmallMovies"></param>/// <returns></returns>public async Task<TaskInfo> InsertDocument<T>(List<T> datasetSmallMovies,string indexName){var index = DefaultClient.Index(indexName);var task = await index.AddDocumentsAsync<T>(datasetSmallMovies);return task;}/// <summary>/// 基本查询/// </summary>/// <param name="searchText"></param>/// <returns></returns>public async Task<List<T>> BasicSearch<T>(string searchText,string indexName){var index = DefaultClient.Index(indexName);ISearchable<T> movies = await index.SearchAsync<T>(searchText);return movies.Hits.ToList();}/// <summary>/// 高亮基本查询/// </summary>/// <param name="searchText"></param>/// <returns></returns>public async Task<List<T>> HighlightBasicSearch<T>(string searchText,string indexName){var index = DefaultClient.Index(indexName);ISearchable<T> movies = await index.SearchAsync<T>(searchText,new SearchQuery{//AttributesToHighlight = new string[] { "title" },AttributesToHighlight = ["*"],HighlightPreTag = "<ellis>",HighlightPostTag = "</ellis>"});return movies.Hits.ToList();}/// <summary>/// 设置搜索字段,设置filter字段/// </summary>/// <returns></returns>public async Task<TaskInfo> UpdateIndexConfig(){var index = DefaultClient.Index("small_movies");return await index.UpdateSettingsAsync(new Settings(){FilterableAttributes = new string[] { "id", "release_date" },SearchableAttributes = new string[] { "title" },DisplayedAttributes = new string[] { "title", "release_date", "id" , "poster", "overview", "genre" }});}/// <summary>/// query 以及filter/// </summary>/// <returns></returns>public async Task<List<DatasetSmallMovie>> QueryByFilter(){var index = DefaultClient.Index("small_movies");return index.SearchAsync<DatasetSmallMovie>("", new SearchQuery(){Filter = "id=338952 AND release_date=1542153600",Limit = 10,Offset = 0}).Result.Hits.ToList();}/// <summary>/// 创建索引的同时指定主键字段/// </summary>/// <param name="indexName"></param>/// <param name="primaryKey"></param>/// <returns></returns>public async Task<TaskInfo> CreateIndex(string indexName,string primaryKey){return await DefaultClient.CreateIndexAsync(indexName, primaryKey);}/// <summary>/// 更新/// </summary>/// <returns></returns>public async Task<TaskInfo> UpdateDocumentByID(){var index = DefaultClient.Index("small_movies");return await index.UpdateDocumentsAsync(new DatasetSmallMovie[] { new DatasetSmallMovie() { Id = "1", Title = "just do it" ,ReleaseDate=DateTime.Now} });}/// <summary>/// 根据ID查询/// </summary>/// <param name="id"></param>/// <returns></returns>public async Task<T> GetByID<T>(string id,string indexName){var index = DefaultClient.Index(indexName);return await index.GetDocumentAsync<T>(id);}public async Task<TaskInfo> DeleteDocuments(string[] ids,string indexName){var index = DefaultClient.Index(indexName);return await index.DeleteDocumentsAsync(ids);}}public class BaseClass{public string Id { get; set; }}public class DatasetSmallMovie:BaseClass{public string Title { get; set; }public string Poster { get; set; }public string Overview { get; set; }[JsonPropertyName("release_date")][JsonConverter(typeof(UnixEpochDateTimeConverter))]public DateTime ReleaseDate { get; set; }public string Genre { get; set; }}//高亮查询使用public class FormattedSmallMovie{public string Id { get; set; }public string Title { get; set; }public string Poster { get; set; }public string Overview { get; set; }[JsonPropertyName("release_date")][JsonConverter(typeof(UnixEpochDateTimeConverter))]public DateTime ReleaseDate { get; set; }public string Genre { get; set; }public DatasetSmallMovie _Formatted { get; set; }}sealed class UnixEpochDateTimeConverter : JsonConverter<DateTime>{static readonly DateTime s_epoch = new DateTime(1970, 1, 1, 0, 0, 0);public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options){if (reader.TokenType == JsonTokenType.String){string stringValue = reader.GetString();var unixTime = Convert.ToInt64(stringValue);return s_epoch.AddMilliseconds(unixTime);}else{var unixTime = reader.GetInt64();return s_epoch.AddMilliseconds(unixTime);}}public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options){var unixTime = Convert.ToInt64((value - s_epoch).TotalMilliseconds);writer.WriteNumberValue(unixTime);}}
}

官网
源码
https://www.meilisearch.com/docs/reference/api/search

https://github.com/meilisearch/meilisearch-dotnet/issues/315


http://www.ppmy.cn/ops/149636.html

相关文章

【Linux】传输层协议TCP

目录 TCP协议 TCP协议段格式 确认应答(ACK)机制 超时重传机制 连接管理机制 理解TIME_WAIT状态并解决由此引起的bind失败的方法 流量控制 滑动窗口 拥塞控制 延迟应答 捎带应答 面向字节流 粘包问题 TCP异常情况 TCP/UDP对比 用UDP实现可靠传输 TCP协议 TCP协…

【机器学习】聚类评价指标之福尔克斯–马洛斯指数(Fowlkes–Mallows Index, FMI)

福尔克斯–马洛斯指数&#xff08;Fowlkes–Mallows Index, FMI&#xff09;是一种用于评估聚类结果与实际标签之间一致性的指标。FMI 值可以用于衡量聚类的准确性&#xff0c;特别是在有真值标签的监督评估场景中。 计算公式 FMI 的计算基于以下公式&#xff1a; 其中&#…

winform第三方界面开源库AntdUI的使用教程保姆级环境设置篇

1. AntdUI 1.1. 导入项目 1.1.1. 首先新建一个空白的基于.net的Winfrom项目1.1.2. 复制AntdUI中src目录到我们的解决方案下面1.1.3. 解决方案下添加现有项目1.1.4. 添加项目引用 1.2. 编写代码 1.2.1. 改写Form1类&#xff0c;让其继承自public partial class Form1 : AntdUI.W…

25/1/11 算法笔记 Yolov8物体识别

这几天做了给Yolov8检测物体的小任务&#xff0c;今天来做下总结。 首先介绍下整个Yolov8检测的步骤吧&#xff0c;安装库那些就不讲了。 这是我的文件包的对象树。 有images包&#xff0c;里面装了训练和验证的图像。 labels包&#xff0c;装了标注好的labels的txt文件&…

MongoTemplate 性能优化指南

MongoTemplate 性能优化指南 1. 查询优化 1.1 合理使用索引 为经常查询的字段创建索引使用复合索引优化多字段查询避免使用无索引的排序操作 // 创建索引示例 mongoTemplate.indexOps(Collection.class).ensureIndex(new Index().on("field1", Sort.Direction.AS…

【redis】centos7下安装redis7

在CentOS 7下安装Redis7可以通过以下两种方法实现&#xff1a;手动编译安装和使用YUM进行安装。 CentOS 7系统的环境和版本&#xff1a; $ cat /etc/centos-release CentOS Linux release 7.9.2009 (Core)手动编译安装 参考官方文档&#xff1a;https://redis.io/docs/lates…

Jenkins持续集成与交付安装配置

Jenkins 是一款开源的持续集成&#xff08;CI&#xff09;和持续交付&#xff08;CD&#xff09;工具&#xff0c;它主要用于自动化软件的构建、测试和部署流程。为项目持续集成与交付功能强大的应用。下面我们来介绍下它的安装与配置。 环境准备 更新系统组件&#xff08;这…

Docker 容器管理

容器是一个 image 的实例&#xff0c;它是我们用 image 文件生成出来的具体应用。 Nginx 服务器 我们在 pull 一个 Nginx image 到本地电脑&#xff0c;用它举例在介绍一些常用的容器管理命令。 // 获取 nginx 镜像 sudo docker pull nginx// 运行 nginx 镜像 sudo docker r…