Elasticsearch 和关系数据库之间的一个重要区别是 Elasticsearch 无法执行联接。在elasticsearch中,您总是搜索单个索引或索引联合。但在父/子关系的情况下,可以使用子索引上的查询来限制父索引中的结果。例如,您可以在account
type.
{
"bool": {
"must": [
{
"text" : { "name": "foo" }
}, {
"term" : { "state": "active" }
}, {
"has_child": {
"type": "email",
"query": {
"text": {"email": "bar" }
}
}
}
]
}
}
此查询将仅返回父文档(不会返回子文档)。您可以使用此查询返回的父级 ID 来使用该字段查找该父级的所有子级_parent
,默认情况下存储并建立索引。
{
"term" : { "_parent": "1" }
}
或者您可以将结果限制为仅包含包含该词的子项bar
在该领域email
:
{
"bool": {
"must": [
{
"term" : { "_parent": "1" }
}, {
"text" : { "email": "bar" }
}
]
}
}
我认为除非您使用的是,否则不可能在 json 中指定父级_批量索引 http://www.elasticsearch.org/guide/reference/api/bulk.html.
这是使用问题中提供的测试数据来实现电子邮件查找的方法:
#!/bin/sh
curl -XDELETE 'http://localhost:9200/test' && echo
curl -XPOST 'http://localhost:9200/test' -d '{
"settings" : {
"number_of_shards" : 1,
"number_of_replicas" : 0
},
"mappings" : {
"account" : {
"_source" : { "enabled" : true },
"properties" : {
"name": { "type": "string", "analyzer": "standard" },
"statuses": { "type": "string", "index": "not_analyzed" }
}
},
"email" : {
"_parent" : {
"type" : "account"
},
"properties" : {
"email": { "type": "string", "analyzer": "standard" }
}
}
}
}' && echo
curl -XPUT 'http://localhost:9200/test/account/1' -d '{
"name": "John Smith",
"statuses": "active"
}'
curl -XPUT 'http://localhost:9200/test/account/2' -d '{
"name": "Peter Smith",
"statuses": "active"
}'
curl -XPUT 'http://localhost:9200/test/account/3' -d '{
"name": "Andy Smith",
"statuses": "active"
}'
//Set up mapping for parent/child relationship
curl -XPUT 'http://localhost:9200/test/email/1?parent=1' -d '{
"email": "[email protected] /cdn-cgi/l/email-protection"
}'
curl -XPUT 'http://localhost:9200/test/email/2?parent=1' -d '{
"email": "[email protected] /cdn-cgi/l/email-protection"
}'
curl -XPUT 'http://localhost:9200/test/email/3?parent=1' -d '{
"email": "[email protected] /cdn-cgi/l/email-protection"
}'
curl -XPUT 'http://localhost:9200/test/email/4?parent=2' -d '{
"email": "[email protected] /cdn-cgi/l/email-protection"
}'
curl -XPUT 'http://localhost:9200/test/email/5?parent=3' -d '{
"email": "[email protected] /cdn-cgi/l/email-protection"
}'
curl -XPUT 'http://localhost:9200/test/email/6?parent=3' -d '{
"email": "[email protected] /cdn-cgi/l/email-protection"
}'
curl -XPOST 'http://localhost:9200/test/_refresh'
echo
curl 'http://localhost:9200/test/account/_search' -d '{
"query": {
"bool": {
"must": [
{
"term": {
"statuses": "active"
}
}
],
"should": [
{
"prefix": {
"name": "a"
}
},
{
"has_child": {
"type": "email",
"query": {
"prefix": {
"email": "a"
}
}
}
}
],
"minimum_number_should_match" : 1
}
}
}' && echo