我建议您使用嵌套对象Meeting
来处理和之间的关系Attendee
。这意味着我们会将所有数据存储在一个文档(会议)中。
会议和与会者类:
public class Meeting
{
public int Id { get; set; }
public string Name { get; set; }
[ElasticProperty(Type = FieldType.Nested)]
public List<Attendee> MeetingAttendees { get; set; }
}
public class Attendee
{
public int Id { get; set; }
public string Name { get; set; }
}
创建索引:
var indicesOperationResponse = client.CreateIndex(descriptor => descriptor
.Index(indexName)
.AddMapping<Meeting>(m => m.MapFromAttributes()));
索引一些数据:
var david = new Attendee {Id = 1, Name = "David"};
var carl = new Attendee {Id = 2, Name = "Carl"};
var jason = new Attendee {Id = 3, Name = "Jason"};
client.Index(new Meeting {Id = 1, Name = "Meeting1", MeetingAttendees = new List<Attendee>{david, carl}});
client.Index(new Meeting {Id = 2, Name = "Meeting2", MeetingAttendees = new List<Attendee>{jason}});
client.Index(new Meeting {Id = 3, Name = "Meeting3", MeetingAttendees = new List<Attendee>{jason, david}});
client.Refresh();
我们应该稍微修改一下您的查询:
var result = client.Search<Meeting>(s => s
.From(0)
.Size(10)
.Query(q => q.Nested(n => n
.Path(p => p.MeetingAttendees.First())
.Query(qq => qq
.Term(meeting => meeting.OnField(f => f.MeetingAttendees.First().Name).Value("david"))))));
弹性搜索的结果:
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 1.4054651,
"hits": [
{
"_index": "my_index",
"_type": "meeting",
"_id": "1",
"_score": 1.4054651,
"_source": {
"id": 1,
"name": "Meeting1",
"meetingAttendees": [
{
"id": 1,
"name": "David"
},
{
"id": 2,
"name": "Carl"
}
]
}
},
{
"_index": "my_index",
"_type": "meeting",
"_id": "3",
"_score": 1.4054651,
"_source": {
"id": 3,
"name": "Meeting3",
"meetingAttendees": [
{
"id": 3,
"name": "Jason"
},
{
"id": 1,
"name": "David"
}
]
}
}
]
}
}
更新:
在您要索引更多相关数据的情况下,查看父子关系可能是值得的
示例类:
public class Meeting
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Attendee
{
public int Id { get; set; }
public string Name { get; set; }
}
映射:
var indicesOperationResponse = client.CreateIndex(descriptor => descriptor
.Index(indexName)
.AddMapping<Meeting>(m => m.MapFromAttributes())
.AddMapping<Attendee>(m => m.MapFromAttributes().SetParent<Meeting>()));
样本数据:
var david = new Attendee { Id = 1, Name = "David"};
var carl = new Attendee { Id = 2, Name = "Carl"};
var jason = new Attendee {Id = 3, Name = "Jason"};
client.Index(new Meeting {Id = 1, Name = "Meeting1"});
client.Index(new Meeting {Id = 2, Name = "Meeting2"});
client.Index(new Meeting {Id = 3, Name = "Meeting3"});
client.Index(david, descriptor => descriptor.Parent("1"));
client.Index(carl, descriptor => descriptor.Parent("1"));
client.Index(jason, descriptor => descriptor.Parent("2"));
client.Refresh();
现在,我们必须通过他们的孩子找到父母。使用 NEST,您可以通过以下查询执行此操作:
var searchResponse = client.Search<Meeting>(s => s
.Query(q => q
.HasChild<Attendee>(c => c
.Query(query => query.Term(t => t.OnField(f => f.Name).Value("david"))))));