gpt4 book ai didi

.net - 如何在 Elasticsearch 的 Nest.Net 中搜索 GUID?

转载 作者:行者123 更新时间:2023-11-29 02:53:50 25 4
gpt4 key购买 nike

我正在使用 Nest,它是 elasticsearch 的 .Net 客户端。搜索 GUID 时遇到问题。由于 GUID 有“-”,elasticsearch 正在考虑作为 token 。

下面是我面临的问题。

我有一个具有以下属性的实体“Employee”。

   Id : Guid 
Name : varchar
DepartmentId : Guid (E.g cb5d39ee-05f0-4351-baba-8eed6c9111ad)

现在我需要获取属于特定部门的员工列表。所以我将传递部门 ID。

由于 DepartmentId 中有一个“-”,elasticsearch 正在考虑作为分隔符,因此我无法获得结果。

员工类

public class Employee
{
public Guid Id { get; set; }
public string Name { get; set; }
[ElasticProperty(Analyzer = "keyword")]
public Guid DepartmentId { get; set; }
}

下面是示例代码。

 class Program
{
static string indexName = "Elasticsearchsamples".ToLowerInvariant();

private static void IndexEmployees()
{
List<Employee> employees = new List<Employee>();
Employee employee;

var deptId = new Guid("cb5d39ee-05f0-4351-baba-8eed6c9111ad");

employee = new Employee()
{
Id = Guid.NewGuid(),
Name = "Raja",
DepartmentId = deptId
};
employees.Add(employee);

employee = new Employee()
{
Id = Guid.NewGuid(),
Name = "Ram",
DepartmentId = deptId
};
employees.Add(employee);

employee = new Employee()
{
Id = Guid.NewGuid(),
Name = "Guru",
DepartmentId = Guid.NewGuid()
};
employees.Add(employee);

if (SearchClient.IsConnected())
{
SearchClient.ElasticClientInstance.DeleteIndex(indexName);

var result = SearchClient.ElasticClientInstance.IndexMany(employees, indexName);
}
}

private static void SearchEmployees()
{

var searchDescriptor = new SearchDescriptor<Employee>();
searchDescriptor.Index(indexName);
var deptId = new Guid("cb5d39ee-05f0-4351-baba-8eed6c9111ad");
searchDescriptor.Query(qq => qq.Term(x => x.DepartmentId, deptId.ToString().ToLowerInvariant()));
//searchDescriptor.Query(qq => qq.Term(x => x.Name, "raja"));

var result = SearchClient.ElasticClientInstance.Search(searchDescriptor);
Console.WriteLine(result.Total);
}

static void Main(string[] args)
{
System.Net.ServicePointManager.Expect100Continue = false;
IndexEmployees();
SearchEmployees();
Console.Read();
}
}

最佳答案

在您的 Employee 类中,您需要告诉 Elasticsearch 要么不分析 DepartmentId 字段,要么使用关键字分析器。请注意 keyword 的文档分析器建议如下:

An analyzer of type keyword that "tokenizes" an entire stream as a single token. This is useful for data like zip codes, ids and so on. Note, when using mapping definitions, it might make more sense to simply mark the field as not_analyzed.

您可以执行以下任一操作:

 //do not analyze the value
[ElasticProperty(Index = FieldIndexOption.not_analyzed)]
public Guid DepartmentId;

//use keyword analyzer
[ElasticProperty(Analyzer = "keyword")]
public Guid DepartmentId;

关于.net - 如何在 Elasticsearch 的 Nest.Net 中搜索 GUID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24185365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com