elasticsearch和关系数据库之间的重要区别是elasticsearch无法执行联接。在elasticsearch中,您始终在搜索单个索引或索引并集。但是在父/子关系的情况下,可以使用对子索引的查询来限制父索引中的结果。例如,您可以对
account类型执行此查询。
{ "bool": { "must": [ { "text" : { "name": "foo" } }, { "term" : { "state": "active" } }, { "has_child": { "type": "email", "query": { "text": {"email": "bar" } } } } ] }}该查询将仅返回父文档(不返回子文档)。您可以使用此查询返回的父代ID,使用field来查找该父代的所有子代,
_parent默认情况下,该字段已存储并建立索引。
{ "term" : { "_parent": "1" } }或者,您可以将结果只限于包含
bar该字段中单词的子级
{ "bool": { "must": [ { "term" : { "_parent": "1" } }, { "text" : { "email": "bar" } } ] }}我认为除非您使用_bulk
indexing,否则无法在json中指定parent
。
这是使用问题中提供的测试数据可以实现电子邮件查找的方式:
#!/bin/shcurl -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" } } } }}' && echocurl -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 relationshipcurl -XPUT 'http://localhost:9200/test/email/1?parent=1' -d '{ "email": "john@smith.com"}'curl -XPUT 'http://localhost:9200/test/email/2?parent=1' -d '{ "email": "admin@mycompany.com"}'curl -XPUT 'http://localhost:9200/test/email/3?parent=1' -d '{ "email": "abcd@efg.com"}'curl -XPUT 'http://localhost:9200/test/email/4?parent=2' -d '{ "email": "peter@peter.com"}'curl -XPUT 'http://localhost:9200/test/email/5?parent=3' -d '{ "email": "andy@yahoo.com"}'curl -XPUT 'http://localhost:9200/test/email/6?parent=3' -d '{ "email": "support@mycompany.com"}'curl -XPOST 'http://localhost:9200/test/_refresh'echocurl '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


