You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 08:22:35