1 回答
- 最新
- 投票最多
- 评论最多
0
Hello,
To perform knn field search using .Net, you can utilise the "OpenSearch .NET clients". I have provided a sample below:
Firstly I have created an index with the below setting:
PUT my-index
{
"settings": {
"index.knn": true
},
"mappings": {
"properties": {
"my_vector1": {
"type": "knn_vector",
"dimension": 2
},
"my_vector2": {
"type": "knn_vector",
"dimension": 4
}
}
}
}
Then I have ingested some sample data using _bulk request as shown below:
POST _bulk
{ "index": { "_index": "my-index", "_id": "1" } }
{ "my_vector1": [1.5, 2.5], "price": 12.2 }
{ "index": { "_index": "my-index", "_id": "2" } }
{ "my_vector1": [2.5, 3.5], "price": 7.1 }
{ "index": { "_index": "my-index", "_id": "3" } }
{ "my_vector1": [3.5, 4.5], "price": 12.9 }
{ "index": { "_index": "my-index", "_id": "4" } }
{ "my_vector1": [5.5, 6.5], "price": 1.2 }
{ "index": { "_index": "my-index", "_id": "5" } }
{ "my_vector1": [4.5, 5.5], "price": 3.7 }
{ "index": { "_index": "my-index", "_id": "6" } }
{ "my_vector2": [1.5, 5.5, 4.5, 6.4], "price": 10.3 }
{ "index": { "_index": "my-index", "_id": "7" } }
{ "my_vector2": [2.5, 3.5, 5.6, 6.7], "price": 5.5 }
{ "index": { "_index": "my-index", "_id": "8" } }
{ "my_vector2": [4.5, 5.5, 6.7, 3.7], "price": 4.4 }
{ "index": { "_index": "my-index", "_id": "9" } }
{ "my_vector2": [1.5, 5.5, 4.5, 6.4], "price": 8.9 }
After this, I have used the below sample code to perform knn search. Kindly, modify the code based on your requirement:
using OpenSearch.Net ;
using OpenSearch.Client;
using OpenSearch.Net .Auth.AwsSigV4;
namespace vs;
class Program
{
public static void Main(string[] args)
{
// Create a client with custom settings
var uri = new Uri("https://search-xxxx.region.es.amazonaws.com ");
var connection = new AwsSigV4HttpConnection();
var settings = new ConnectionSettings(uri, connection);
var client = new OpenSearchLowLevelClient(settings);
Console.WriteLine("knn query search sample");
var searchResponse = client.Search <StringResponse>("my-index",
@"{
""size"": 2,
""query"": {
""knn"": {
""my_vector2"": {
""vector"": [2, 3, 5, 6],
""k"": 2
}
}
}
}");
Console.WriteLine(searchResponse.Body);
}
}
Dependencies:
- Opensearch.Net NuGet: https://www.nuget.org/packages/OpenSearch.Net
- OpenSearch.Client NuGet: https://www.nuget.org/packages/OpenSearch.Client/
- OpenSearch.Net.Auth.AwsSigV4 NuGet: https://www.nuget.org/packages/OpenSearch.Net.Auth.AwsSigV4
Reference:
- k-Nearest Neighbor (k-NN) search in Amazon OpenSearch Service - https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html
- OpenSearch .NET clients - https://opensearch.org/docs/latest/clients/dot-net/
- OpenSearch .NET sample program - https://opensearch.org/docs/latest/clients/OpenSearch-dot-net/#sample-program
相关内容
- AWS 官方已更新 10 个月前
- AWS 官方已更新 3 年前
- AWS 官方已更新 3 年前