python mysqlx.Result.get_autoincrement_value() 不起作用

python mysqlx.Result.get_autoincrement_value() doesn't work

我正在尝试在我的 python 项目(python 3.8)中使用 MySQL 8 的文档存储。 MySQL-connector python 的版本是 8.0.20。根据 API reference and the X DevAPI User Guide,我试图在将文档添加到数据库后获取自动递增的文档 ID。每次执行后,数据都会成功插入DB,但调用get_autoincrement_value()后会返回'-1'。

我的代码如下:

    try:
        schema = session.get_schema('my_schema')
        collection = schema.get_collection('my_collection')
        topic_dict = protobuf_to_dict(topic)
        doc_id = collection.add(topic_dict).execute().get_autoincrement_value()
        logger.debug('doc_id: {}', doc_id)
        return doc_id
    except Exception as e:
        logger.exception("failed to add topic to db, topic: {}, err: {}", topic, e)

我的使用有什么问题吗?谢谢大家~

您似乎对自动生成的文档 ID 感兴趣。如果是这种情况,您应该改用 get_generated_ids:

doc_id = collection.add(topic_dict).execute().get_generated_ids()[0]

在这种情况下,方法 returns 是在 add() 操作范围内生成的所有 ID 的列表。

文档可能不够清楚,但是 get_auto_increment_value() 仅在您插入包含 session.sql() or table.insert() on a table containing an AUTO_INCREMENT 列的行时包含有用的数据。它在 NoSQL 集合的范围内没有任何意义,因为最后一个集合只是一个 table 创建的(压缩版本):

CREATE TABLE collection (
  `doc` json DEFAULT NULL,
  `_id` varbinary(32),
  PRIMARY KEY (`_id`)
)

这意味着没有任何东西可以“自动递增”。

免责声明:我是 MySQL X DevAPI Connector for Node.js

的首席开发人员