.Net使用Elastic.Clients.Elasticsearch在Elasticsearch8中实现向量存储和相似度检索

ops/2024/9/23 3:52:30/

文章目录

      • 一、测试环境
      • 二、代码
        • 1、创建包含DenseVector的索引
        • 2、索引文档
        • 3、对向量字段进行近似knn检索
      • 三、参考

一、测试环境

Elastic.Clients.Elasticsearch版本:8.13.0
Elasticsearch版本:8.13.0

二、代码

1、创建包含DenseVector的索引
public static bool InitIndex()
{// 定义索引配置var faceVectorproperties = new Properties{{ "Id" ,new KeywordProperty()},{ "FileID" ,new KeywordProperty()},{ "FileGUID" ,new KeywordProperty()},{ "ResourceID" ,new KeywordProperty()},{ "FileName" ,new TextProperty()},{ "Embedding" ,new DenseVectorProperty{Dims = 3 } }};// 定义索引配置var indexConfig = new IndexState{Settings = new IndexSettings{NumberOfShards = 1, // 设置分片数NumberOfReplicas = 1 // 设置副本数},Mappings = new TypeMapping{Properties = faceVectorproperties}};//判断是否已经存在该索引var existFaceVectorIndexResponse = _client.Indices.ExistsAsync("FaceVector").Result;if (!existFaceVectorIndexResponse.IsValidResponse){// 创建索引请求var createIndexRequest = new CreateIndexRequest("FaceVector"){Settings = indexConfig.Settings,Mappings = indexConfig.Mappings};var createFaceVectorIndexResponse = _client.Indices.CreateAsync(createIndexRequest).Result;if (createFaceVectorIndexResponse.Acknowledged){//添加一条测试数据ES_FaceVector temp = new ES_FaceVector{FileID = 0,FileGUID = Guid.NewGuid(),ResourceID = 0,FileName = "测试",Embedding = new float[] {1.2f,1.1f,1.3f }};var addDocResult = AddDoc<ES_FaceVector>(temp, ElasticIndexEnum.FaceVector);}else{return false;}}return true;
}
2、索引文档
//批量索引文档
public static bool AddDocs<T>(List<T> data, string indexName) where T : class
{var bulkIndexResponse = _client.BulkAsync(b => b.Index(indexName).IndexMany(data)).Result;return bulkIndexResponse.IsValidResponse;
}
//单个索引文档
public static bool AddDoc<T>(T data, string indexName) where T : class
{var response = _client.IndexAsync(data, indexName).Result;return response.IsValidResponse;
}
3、对向量字段进行近似knn检索
public static void SearchKnn()
{// 构建KNN查询var doubleArr = new[] { -0.04604065, 0.054946236, 0.057453074};var arrLen = doubleArr.Length;var knnQuery = new KnnQuery(){k = 2,NumCandidates = 1000,Field = "embedding",QueryVector= doubleArr.Select(s=>(float)s).ToArray()};// 构建Elasticsearch查询var searchRequest = new SearchRequest<ES_FaceVector>(ElasticIndexEnum.FaceVector){Knn = new KnnQuery[] { knnQuery },MinScore = 0.90,SourceIncludes = new [] { "fileName", "embedding" }};var searchResponse = _client.Search<ES_FaceVector>(searchRequest);if (searchResponse.IsValidResponse){foreach (var hit in searchResponse.Hits){// 处理每个文档的结果var fileNameTemp = hit.Source.FileName;var embeddingTemp = hit.Source.Embedding;}}else{Console.WriteLine($"Error: {searchResponse.DebugInformation}");}
}

三、参考

.Net使用Elastic.Clients.Elasticsearch连接Elasticsearch8

https://www.elastic.co/guide/en/elasticsearch/client/net-api/8.13/connecting.html

https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html

https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html



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

相关文章

springboot笔记一:idea社区版本创建springboot项目的方式

社区idea 手动maven 创建springboot项目 创建之后修改pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:sc…

stable-diffusion教程

下载代码 https://gitee.com/stable_diffusion/stable-diffusion-webui.git 然后执行自动安装环境命令 ./webui.sh

jenkins自动化举例

使用 Jenkins 可以显著提高工作效率&#xff1a; 1. **自动化构建**&#xff1a; - 假设您是一个开发人员&#xff0c;需要频繁地编译和测试代码。手动执行这些任务可能会非常耗时。使用 Jenkins&#xff0c;您可以设置自动化构建流程&#xff0c;每当您提交新代码时&#…

excel文件导入dbeaver中文乱码

1.将excel文件进行另存为&#xff0c;保存类型选择【CSV】 2.选择【工具】–>【web选项】–> 【编码】–> 【简体中文&#xff08;GB18030&#xff09;】 3.在DBeaver进行数据导入 直接导入应该就可以&#xff0c;如果不行的话按下面处理。 选择【导入数据——选择cs…

FPGA 以太网概念简单学习

1 MAC和PHY 从硬件的角度来说&#xff0c;以太网接口电路主要由 MAC &#xff08; Media Access Control &#xff09;控制器和物理层接口 PHY&#xff08;Physical Layer &#xff0c; PHY &#xff09;两大部分构成。 MAC 指媒体访问控制子层协议&#xff0c;它和 PHY 接…

js深浅拷贝

目录 引用关系深拷贝基本实现类型处理循环引用key为symbol时structedClone 引用关系 我们知道&#xff0c;像对象这种复杂数据类型&#xff0c;在定义它的时候我们所指定的变量只会存储这个对象的地址&#xff0c;我们通过这个地址来寻找对象并且操作它&#xff0c;而将这个变…

Linux系统——Nginx常见面试题

目录 一、Nginx使用场景 二、Nginx的发展历史 三、Nginx没出现之前都存在过什么问题 四、Nginx的优点 五、正向代理和反向代理分别是什么 六、Nginx限流问题 七、Nginx动静分离 八、什么是负载均衡 九、Nginx负载均衡的策略有哪些 十、Nginx多进程模型 十一、为什么…

【基础算法】二分查找

1.二分查找 二分查找 思路&#xff1a; 朴素二分模版 class Solution { public:int search(vector<int>& nums, int target) {int l 0, r nums.size() - 1;while(l < r){int mid (l r) / 2;if(nums[mid] < target) l mid 1;else if(nums[mid] > ta…