使用 python 从 couchbase 集合中提取文档

Extract document from couchbase collection using python

我有一个桶 'A',范围 'B' 和集合 'C'。我如何从 couchbase 检索此集合中的所有文档?

import pandas as pd
from couchbase_core.cluster import PasswordAuthenticator
from couchbase.cluster import Cluster, ClusterOptions, QueryOptions
 
cluster = Cluster('couchbase://localhost', ClusterOptions(PasswordAuthenticator('xxx', 'xxx')))
cb = cluster.bucket("A")


cb_coll = cb.scope("B").collection("C")

如何使用 python 从这个集合 'C' 中提取所有文档并将其保存到数据框中?

如果您要从 collection 中寻找类似 select * 的内容, 您需要在 collection.

上创建主索引
CREATE PRIMARY INDEX ON `A`.B.C;
SELECT * FROM A.B.C;

可以使用 Couchbase 网络界面创建主索引。

要使用 Python SDK 执行这些操作,您可以 运行 使用集群 object 进行查询。请注意,索引创建是一个异步操作。

from couchbase.exceptions import QueryIndexAlreadyExistsException

# Create Primary Index for querying
try:
   cluster.query("CREATE PRIMARY INDEX ON A.B.C")
except QueryIndexAlreadyExistsException:
   print("Index already exists")

# Query all documents
result = cluster.query("SELECT * from A.B.C")
# Get all the documents
results = [row for row in result]
# Convert the results into a Pandas Dataframe
results_df = pd.DataFrame(results)