postgres 9.1全文搜索没有返回结果

时间:2012-12-08 14:28:53

标签: postgresql full-text-search full-text-indexing psql tsvector

我已经在网上搜索了好几天似乎互联网从来没有听说过我的问题:

我有一个邮政地址数据库表,其中包含大约37M的英国记录,其中包含地理空间索引和衍生的全文索引,如下所示:

create index on gb_locations using gin(to_tsvector('english', "Postcode" || ' ' || "Postcode_outcode" || ' ' || "Road" || ' ' || "Neighbourhood" || ' ' || "Admin2" || ' ' || "Admin3");)

我的全文搜索格式为:

SELECT * FROM gb_locations
WHERE
    to_tsvector('english', "Postcode" || ' ' || "Postcode_outcode" || ' ' || "Road" || ' ' || "Neighbourhood" || ' ' || "Admin2" || ' ' || "Admin3") @@ plainto_tsquery('english', 'greenham road rg14')

该查询适用于大多数英国地址,特别是在伦敦地区,但对于更远的地方,查询不会返回任何结果。

我已经验证表中存在记录,因为我可以使用地理空间搜索找到它,但对于全文搜索,似乎数据库不知道它。

这是解释:

Bitmap Heap Scan on gb_locations  (cost=52.04..56.10 rows=1 width=521)
  Recheck Cond: (to_tsvector('english'::regconfig, ((((((((((("Postcode")::text || ' '::text) || ("Postcode_outcode")::text) || ' '::text) || "Road") || ' '::text) || ("Neighbourhood")::text) || ' '::text) || ("Admin2")::text) || ' '::text) || ("Admin3")::text)) @@ '''greenham'' & ''road'' & ''rg14'''::tsquery)
  ->  Bitmap Index Scan on text_search_index  (cost=0.00..52.04 rows=1 width=0)
        Index Cond: (to_tsvector('english'::regconfig, ((((((((((("Postcode")::text || ' '::text) || ("Postcode_outcode")::text) || ' '::text) || "Road") || ' '::text) || ("Neighbourhood")::text) || ' '::text) || ("Admin2")::text) || ' '::text) || ("Admin3")::text)) @@ '''greenham'' & ''road'' & ''rg14'''::tsquery)

任何投手都会非常感激。

2 个答案:

答案 0 :(得分:5)

如果某些字段可以为NULL,则需要在获取要搜索的字符串的全局串联中对它们应用coalesce(field, '')

否则它似乎与评论中给出的示例值一起使用:

select to_tsvector('english','RG147SW RG14 Greenham Road Newbury  West Berkshire')
  @@ plainto_tsquery('english', 'greenham road rg14');

 ?column? 
----------
 t
(1 row)

但是这一个不匹配(结果为NULL),这就是Admin2为NULL时的情况,或者更常见的是将任何其他字段传递给||运算符。< / p>

   select to_tsvector('english','RG147SW RG14 Greenham Road ' || NULL || ' Newbury  West Berkshire')
      @@ plainto_tsquery('english', 'greenham road rg14');

?column? 
----------

(1 row)

答案 1 :(得分:3)

只是添加DanielVérité所说的,

如果要求任何字段为NULL,则必须按如下方式创建全文索引:

create index [index name] on [table name] using gin(to_tsvector('english', coalesce("Field1",'') || ' ' || coalesce("Field2",'') || ' ' || coalesce("Field3",'') ....));

此外,必须在查询本身中使用相同的模板,如下所示:

SELECT * FROM [table name] WHERE to_tsvector('english', coalesce("Field1",'') || ' ' || coalesce("Field2",'') || ' ' || coalesce("Field3",'') ....) @@ plainto_tsquery('english', '[your search sentance/phrase]');