如何使用Atlas Search同时搜索根文档与embeddedDocuments字段
问题描述
我的集合中有如下文档:
{ "_id": "101", "PublisherName": "Big book publishers", "Books": [ { "_id": "6791913210", "Title": "Piano made simple", "Author": "John Bent" }, { "_id": "6638200210", "Title": "Guitar made simple", "Author": "Kim Larry" } ] }
定义的搜索索引如下:
{ "mappings": { "dynamic": false, "fields": { "PublisherName": { "analyzer": "lucene.standard", "type": "string" }, "Books": { "dynamic": false, "fields": { "Author": { "analyzer": "lucene.standard", "type": "string" } }, "type": "embeddedDocuments" } } } }
可以单独搜索PublisherName或Books.Author字段:
- 搜索PublisherName
{ "index": "book-search-Index", "text": { "query": "Big book publishers", "path": ["PublisherName"] } }
- 搜索Books.Author
{ "index": "book-search-Index", "embeddedDocument": { "path": "Books", "operator": { "text": { "path": ["Books.Author"], "query": "Guitar" } } } }
但尝试同时搜索两个字段时触发错误:
Reason: at most one of [autocomplete, compound, embeddedDocument, equals, exists, geoShape, geoWithin, in, knnBeta, moreLikeThis, near, phrase, queryString, range, regex, search, span, term, text, wildcard] may be present
错误的搜索语句:
{ "index": "book-search-Index", "text": { "query": "Big book publishers", "path": ["PublisherName"] } "embeddedDocument": { "path": "Books", "operator": { "text": { "path": ["Books.Author"], "query": "Guitar" } } } }
解决方案
要同时搜索顶层字段和嵌套文档字段,必须使用compound操作符来组合多个查询条件,它支持通过must、should等逻辑关联不同的查询规则。
示例查询语句:
{ "index": "book-search-Index", "compound": { "must": [ { "text": { "query": "Big book publishers", "path": ["PublisherName"] } }, { "embeddedDocument": { "path": "Books", "operator": { "text": { "path": ["Books.Author"], "query": "Guitar" } } } } ] } }
关键说明:
must:所有子条件必须同时满足,对应逻辑与(AND)should:满足任一子条件即可,对应逻辑或(OR)- 所有子查询必须包裹在
compound的数组字段中,不能直接在根节点并列多个查询类型
内容的提问来源于stack exchange,提问作者O'Neil Tomlinson
相关产品推荐
相关产品推荐

