在ElasticSearch上使用elastic4s在嵌套字段上查询
问题描述:
我想查询在ES中编入索引的嵌套文档。在ElasticSearch上使用elastic4s在嵌套字段上查询
例如,嵌套字段是user
,其包含两个字段id
和name
。我想查询名称与字段user.name
完全匹配的所有文档。
无法弄清楚如何使用elastic4s DSL。
答
这是你怎么做嵌套查询在elastic4s:
首先,建立索引,这样你有一个嵌套类型:
client.execute {
create index "nested" mappings {
"show" as {
"actor" typed NestedType
}
}
}
一些样本数据
然后
client.execute(
index into "nested/show" fields(
"name" -> "game of thrones",
"actor" -> Seq(
Map("name" -> "peter dinklage", "birthplace" -> "Morristown"),
Map("name" -> "pedro pascal", "birthplace" -> "Santiago")
)
)
)
然后是关键部分。要进行搜索,您使用nested
(或elastic4s 1.4 beta,nestedQuery
)来“插入”嵌套范围,您可以在其中使用任何标准查询类型进行搜索。在这里,我只是使用简单的termQuery
搜索。
client.execute {
search in "nested/show" query nested("actor").query(termQuery("actor.name" -> "dinklage"))
}
答
如何:
clientProvider.getClient.execute {
(search in path)
.query(
nested("[something].user").query(
bool(must(
term("something.user.name" -> name)
))
)
)
}
由于我不熟悉你的结构,我会提供我自己的例子,也许你可以从那里:
- venueData由荟萃关于场地和场地本身的数据。
- 场地得到了员工的名单是嵌套在NestedType()
- 员工得到了一个ID,它是Long类型
def venueByEmployeeId(employeeId: Long): Future[Option[VenueData]] = {
clientProvider.getClient.execute {
(search in path)
.query(
nested("venue.employees").query(
bool(must(
term("venue.employees.id" -> employeeId)
))
)
)
}.map(_.getHits.jsonToList[VenueData].headOption)
}
我也忘了查询的事情是,您需要编写整个路径(“venue.employees.id” - > employeeId)