Meilisearch ASP.Net Core API 功能demo

  1. 安装
bash 复制代码
MeiliSearch                 0.15.5   0.15.5
  1. demo code
csharp 复制代码
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

相关推荐
GV191rLvq13 小时前
基于Socket实现的最简单的Web服务器【ASP.NET原理分析】
服务器·前端·asp.net
乐观的夕阳15 小时前
ASP.NET 异步页的实现方式
java·数据库·asp.net
管家婆客服中心19 小时前
Server 2016系统安装IIS和ASP.NET框架
asp.net·server 2016
威武的花瓣20 小时前
细说ASP.NET的各种异步操作
后端·asp.net·php
任性的芝麻20 小时前
ASP.NET MVC 中的异步方式
后端·asp.net·mvc
任性的自行车21 小时前
ASP.NET MVC 4路线图
后端·asp.net·mvc
terry60019 天前
5G视频短信服务商选型全攻略:通道资源、架构能力与成本评估2026最新标准
大数据·人工智能·5g·json·asp.net·信息与通信·数据库架构
加号320 天前
【C#】VS2022 传统 ASP.NET Web 服务(.asmx)接口实现指南
前端·c#·asp.net
换个昵称都难20 天前
webrtc RTC_P2P源码解析
asp.net·webrtc·p2p
cjp56022 天前
009. ASP.NET WEB API 用户关联esp32设备
前端·后端·asp.net