Postgres to_tsvector VS :: tsvector

时间:2014-06-04 18:59:57

标签: postgresql

我真的不明白Postgres中to_tsvector::tsvector之间的区别。我阅读了to_tsvector here上的文档,但似乎没有其他文档::tsvector - 这有点问题。它被提到here,但它在查询之前说明了规范化,并且通过to_tsvector进行了规范化。

我创建this SQL Fiddle来证明这两者;如果你不想离开,这里是代码:

DDL

CREATE TABLE text (
  text_id serial PRIMARY KEY,
  source_text text NOT NULL,
  destination_text text NOT NULL
);

SQL

-- Throw some stuff in there
INSERT INTO text (source_text, destination_text) VALUES
('Hello', 'Hello Result'),
('With Comma, Query', 'WithComma, Result');

-- Forced to use punctuation in the query to match what is in the vector
SELECT T.source_text, T.destination_text
FROM   text T
WHERE  LOWER(T.source_text)::tsvector @@ LOWER('Hello')::tsquery;

-- Vector free of punctuation, don't include it in the query
SELECT T.source_text, T.destination_text
FROM   text T
WHERE  to_tsvector(LOWER(T.source_text)) @@ LOWER('Comma')::tsquery;

SELECT ts_debug('english', 'Something without a comma');

SELECT ts_debug('english', 'Something, with a comma');

在我看来,to_tsvector将采用文本,剥去标点符号并返回向量。另一方面,::tsvector似乎在向量中包含标点符号,导致需要在查询中使用相同的标点符号。

两者之间有什么实际差异?一个人通常比另一个更受欢迎吗?在什么情况下每个人都喜欢?

1 个答案:

答案 0 :(得分:10)

to_tsvector(text)读取字符串并对字符串进行一些规范化(将语言设置考虑在内)。

::tsvector是演员。它没有进行任何规范化(并且不关心语言设置)。

请参阅:http://www.postgresql.org/docs/current/interactive/functions-textsearch.html

几年前,我在python中编写了一个自己的to_tsvector(),因为我对postgres处理它的方式不满意。这让我有了更多的控制权。

要将数据插入我使用tsvector强制转换的列:

'UPDATE myapp_mymodel SET content=%s::tsvector where id=%s', [tsvector, self.id])
相关问题