代码之家  ›  专栏  ›  技术社区  ›  Lars Anundskås

Postgresql-全文搜索索引-意外的查询结果

  •  1
  • Lars Anundskås  · 技术社区  · 11 年前

    我有一张桌子,桌子上有一堆可乐 我在一个表上创建了一个全文索引,如下所示:

    CREATE INDEX phrasetable_exp_idx ON msc.mytable 
    USING gin(to_tsvector('norwegian', coalesce(msc.mytable.col1,'') || ' ' || 
                     coalesce(msc.mytable.col2,'') || ' ' || 
                     coalesce(msc.mytable.col3,'') || ' ' ||
                     coalesce(msc.mytable.col4,'') || ' ' ||
                     coalesce(msc.mytable.col5,'') || ' ' ||
                     coalesce(msc.mytable.col6,'') || ' ' ||
                     coalesce(msc.mytable.col7,'')));
    

    我尝试了一些搜索,结果非常快,但是,对于某个特定的搜索,我没有得到预期的结果。 我的表中有一行,其中col1和col2都具有精确的值“Importkompetance Oslo AS” 在col3中,它的值为“9999”。 只有to_tsquery(‘9999’)查询返回该行,这表明它在col1和col2中都有值“Importkompetanse Oslo AS”,但前两个查询没有返回匹配项。

    SELECT *
    FROM msc.mytable
    WHERE to_tsvector('norwegian', coalesce(msc.col1,'') || ' ' || 
                     coalesce(msc.mytable.col2,'') || ' ' || 
                     coalesce(msc.mytable.col3,'') || ' ' ||
                     coalesce(msc.mytable.col4,'') || ' ' ||
                     coalesce(msc.mytable.col5,'') || ' ' ||
                     coalesce(msc.mytable.col6,'') || ' ' ||
                     coalesce(msc.mytable.col7,'')));
    @@ --to_tsquery('Importkompetanse&Oslo&AS') -- nada
       plainto_tsquery('Importkompetanse') -- nada
       --to_tsquery('9999') -- OK!
    

    有人知道为什么我的搜索没有结果吗?

    编辑:

    出于某种原因,to_tsquery返回如下内容: “‘9999’:9‘进口量’:1,6” importkompetance这个词似乎被切断了?

    然而,如果我将它设置为简单而不是挪威语,我会得到预期的结果,一切看起来都很好。为什么?

    1 回复  |  直到 11 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    您在 tsvector tsquery 价值观您应该使用一致的配置,例如:

    select to_tsvector('norwegian', 'Importkompetanse Oslo AS')
           @@ to_tsquery('norwegian', 'Importkompetanse&Oslo&AS');
    

    SQLFiddle

    这就是为什么它与 'simple' 配置(即 default ).

    笔记 :你总是可以 debug 文本搜索 ts_debug() :出厂价。 'Importkompetanse' 尚未被切断, 'importkompetans' 是这个词的恰当词素(在 'norwegian' 配置)。

    :您使用了一个非常长的基于表达式的索引,只有在查询中也使用了精确的表达式时,才会使用该索引。您在示例中正确使用了它,但这会使查询变得非常长,如果稍后更改索引表达式,则需要确保所有“使用”都已更新。

    您可以使用一个简单的(sql)函数来简化查询:

    create or replace function col_tsvector(mytable)
      returns tsvector
      immutable
      language sql
      as $function$
    return to_tsvector('norwegian',
      coalesce($1.col1, '') || ' ' || 
      coalesce($1.col2, '') || ' ' || 
      coalesce($1.col3, '') || ' ' ||
      coalesce($1.col4, '') || ' ' ||
      coalesce($1.col5, '') || ' ' ||
      coalesce($1.col6, '') || ' ' ||
      coalesce($1.col7, ''))
    $function$;
    

    这样,您可以大大简化索引定义和;您的查询也是如此。(您甚至可以使用 attribute notation .)