作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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/
我是一名优秀的程序员,十分优秀!