我正在使用 Scala 和 REST 的 Elasticsearch ,并具有以下数据结构:(作为 JSON 输入文件)
{
"bookTitle" : "textbook",
"bookAuthors" : [
{
"authorId" : "01",
"authorName" : "author1"
},
{
"authorId" : "02",
"authorName" : "author2"
},
]
}
此集合使用的数据映射:
{
"properties" : {
"book": {
"properties": {
"bookTitle": {
"type": "string"
},
"bookAuthors": {
"type": "nested",
"properties": {
"authorId ": {
"type":"string"
},
"authorName" : {
"type": "string"
}
}
}
}
}
}
}
我希望能够通过作者 ID 进行查询并仅获得匹配的单个作者。到目前为止,我已经设法通过 authorId 进行查询,但我一直在获取显示两位作者的整个书籍文档;我还尝试仅选择特定于要显示的 bookAuthors 的字段,但结果是一样的。
现状: 获取 authorId 为 01 的作者姓名 => 返回 [author1,author2]
必填查询: 获取 authorId 为 01 的作者姓名 => return [author1]
最佳答案
在 elasticsearch 1.5.2 中,您可以使用 inner hits 实现此目的
例如:
put mybooks
{
"mappings": {
"book": {
"properties": {
"bookTitle": {
"type": "string"
},
"bookAuthors": {
"type": "nested",
"properties": {
"authorId ": {
"type": "string"
},
"authorName": {
"type": "string"
}
}
}
}
}
}
}
2) 索引文件
put mybooks/book/1
{
"bookTitle": "book1",
"bookAuthors": [
{
"authorId": "01",
"authorName": "author1"
},
{
"authorId": "02",
"authorName": "author2"
}
]
}
put mybooks/book/2
{
"bookTitle" : "book2",
"bookAuthors" : [
{
"authorId" : "03",
"authorName" : "author1"
},
{
"authorId" : "02",
"authorName" : "author2"
}
]
}
3)查询
post mybooks/_search
{
"_source": [
"bookTitle"
],
"query": {
"nested": {
"path": "bookAuthors",
"query": {
"match": {
"bookAuthors.authorId": "02"
}
},
"inner_hits": {
"_source" :["authorName"]
}
}
}
}
4) 结果
"hits": [
{
"_index": "mybooks",
"_type": "book",
"_id": "1",
"_score": 1.4054651,
"_source": {
"bookTitle": "book1"
},
"inner_hits": {
"bookAuthors": {
"hits": {
"total": 1,
"max_score": 1.4054651,
"hits": [
{
"_index": "mybooks",
"_type": "book",
"_id": "1",
"_nested": {
"field": "bookAuthors",
"offset": 1
},
"_score": 1.4054651,
"_source": {
"authorName": "author2"
}
}
]
}
}
}
},
{
"_index": "mybooks",
"_type": "book",
"_id": "2",
"_score": 1.4054651,
"_source": {
"bookTitle": "book2"
},
"inner_hits": {
"bookAuthors": {
"hits": {
"total": 1,
"max_score": 1.4054651,
"hits": [
{
"_index": "mybooks",
"_type": "book",
"_id": "2",
"_nested": {
"field": "bookAuthors",
"offset": 1
},
"_score": 1.4054651,
"_source": {
"authorName": "author2"
}
}
]
}
}
}
}
]
关于json - Elasticsearch 提取内部元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30345142/