c# - 主对象和嵌套对象中的 Elastic Search 2.0 搜索查询
问题描述
这是我的模型:
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Nested]
public List<Subject> Subjects { get; set; }
}
public class Subject
{
public int Id { get; set; }
public string SubjectName { get; set; }
}
映射:
mappings: {
student: {
properties: {
firstName: {
type: "string"
},
id: {
type: "integer"
},
lastName: {
type: "string"
},
subjects: {
type: "nested",
properties: {
id: {
type: "integer"
},
subjectName: {
type: "string"
}
}
}
}
}
}
要在嵌套对象(主题)中搜索,我使用以下代码并正确返回值。
var searchResponse = client.Search<Student>(s => s
.Query(q => q
.Nested(n => n
.Path(p => p.VolunteerTasks)
.Query(nq => nq.Match(m => m
.Query(searchText).Field("subjects.subjectName"))))));
return searchResponse.Documents;
但我想用相同的 searchText 搜索student.firstName
,student.lastName
和subjects.subjectName
. 我怎样才能做到这一点?
解决方案
以 REST API 的形式提供答案,您可以将其转换为 c# 格式,因为我不熟悉它的语法,这对不寻找特定语言答案的人会有所帮助。
用您的示例数据对此进行了测试,下面是工作解决方案。
索引定义
{
"student": {
"properties": {
"firstName": {
"type": "string"
},
"id": {
"type": "integer"
},
"lastName": {
"type": "string"
},
"subjects": {
"type": "nested",
"properties": {
"id": {
"type": "integer"
},
"subjectName": {
"type": "string"
}
}
}
}
}
}
opster
**索引示例文档,其中没有subject
和firstname
**
{
"firstName": "Isuru",
"lastName": "foo",
"id": 1,
"subjects": [
{
"id": 100,
"subjectName": "math"
},
{
"id": 101,
"subjectName": "opster"
}
]
}
索引另一个没有opster
任何主题名称的文档
{
"firstName": "opster",
"lastName": "tel aviv",
"id": 1,
"subjects": [
{
"id": 100,
"subjectName": "math"
},
{
"id": 101,
"subjectName": "science"
}
]
}
搜索查询,请根据您的要求更改must
为should
{
"query": {
"bool": {
"should": [ --> note
{
"match": {
"firstName": "opster"
}
},
{
"nested": {
"path": "subjects",
"query": {
"bool": {
"must": [ -->note
{
"match": {
"subjects.subjectName": "opster"
}
}
]
}
}
}
}
]
}
}
}
搜索结果
"hits": [
{
"_index": "nested",
"_type": "student",
"_id": "1",
"_score": 0.39103588,
"_source": {
"firstName": "opster",
"lastName": "tel aviv",
"id": 1,
"subjects": [
{
"id": 100,
"subjectName": "math"
},
{
"id": 101,
"subjectName": "science"
}
]
}
},
{
"_index": "nested",
"_type": "student",
"_id": "2",
"_score": 0.39103588,
"_source": {
"firstName": "Isuru",
"lastName": "foo",
"id": 1,
"subjects": [
{
"id": 100,
"subjectName": "math"
},
{
"id": 101,
"subjectName": "opster"
}
]
}
}
]
推荐阅读
- html - Figma svg 导出问题
- python - 数据流作业图为空
- browser - 将 SMB 文件从 Web 应用程序拖到本地应用程序,而不是通过下载,而是像文件浏览器一样?
- python - 重构两个 JSON 文件之间的 Python jsondiff 对称差异格式
- python - tkinter 中的动画
- javascript - Muuri 接收事件未触发
- vue.js - 使用 web 组件测试 vue
- flutter - 我正在尝试将这些代码行转换为不可为空的语句
- antd - Antd Menu.Item 中的副标题或子元素
- powershell - 当我调用 New-AzureADuser @param 时,userPrincipalName 属性的域部分无效