PostgreSQL - 无法创建表 - 数据类型点没有用于访问方法“btree”的默认运算符类

Sha*_*eOH 1 python sql postgresql psycopg2

所以我正在做一个项目来学习 SQL、Python 和一些服务器端的东西,经过多次搜索,我在这一点上很难过。我想创建两个相同的表,我有以下代码:

import psycopg2 as db
import json

with open('config.json', 'r') as f:
config = json.load(f)

conn = db.connect(user=config['dbuser'], database=config['dbname'], host=config['dbhost'], password=config['dbpass']);
cur = conn.cursor()

cur.execute("""CREATE TABLE IF NOT EXISTS A 
    (
            city            TEXT,
            location        POINT NOT NULL,
            eta             INTEGER,
            time            TIMESTAMP WITH TIME ZONE NOT NULL,
            holiday         BOOLEAN,
            PRIMARY KEY (location, time)
    );""")
Run Code Online (Sandbox Code Playgroud)

还有表B,格式相同,其中A和B是不同的服务。运行此程序时,我得到:

Traceback (most recent call last):
  File "dbsetup.py", line 18, in <module>
);""")
psycopg2.ProgrammingError: data type point has no default operator class for access method "btree"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.
Run Code Online (Sandbox Code Playgroud)

我一直在寻找一段时间,但我遇到的任何事情都与这种情况非常相似,而且我很困惑,因为我肯定在这里遗漏或误解了一些非常基本的东西。任何帮助/指向正确方向将不胜感激!也非常欢迎一般性建议。

Cra*_*ger 5

PostgreSQL 版本不支持在point数据类型上创建普通或唯一的 b-tree 索引(至少在 9.5 之前为真)。因此,您不能将其point用作PRIMARY KEY.

test=> CREATE TABLE test_table( xy point primary key );
ERROR:  data type point has no default operator class for access method "btree"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.
Run Code Online (Sandbox Code Playgroud)

您需要更改数据模型,以免尝试将 apoint作为 PK 的一部分。

或者你可以写一个扩展,增加了对B树索引支持point的类型,但是这需要大量的更多的工作和PostgreSQL的索引是如何工作的胆量理解。

无论如何,如果您正在做地理方面的工作,您可能需要考虑使用PostGISgeometry数据类型。它具有更丰富的搜索操作集,用于查找最近的点、按距离查找、检查点是否在区域内等,所有这些都有效地索引。

  • 使用 `decimal` 或 `numeric` 对性能来说是非常令人震惊的;如果您需要任意精度和舍入控制,请仅使用十进制浮点类型。我会使用`float8`。但除此之外,是的,这是合理的。 (2认同)