Sqlalchemy全文搜索多列和部分搜索postgresql

时间:2017-11-10 17:31:18

标签: python postgresql sqlalchemy full-text-search

我已经对此进行了大量搜索,但我尚未找到最佳解决方案。假设我们有以下表:

Class User(DeclarativeBase):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)
    description = Column(String)

与用户:

  • 安迪|约翰逊| blah blah blah

  • Andress |布什| blah blah

搜索应包含first_namelast_namedescription列。

我想搜索ohns查询,在我的结果中,我想以某种方式知道匹配的列是什么,并且某种方式结果与完全匹配或部分匹配相匹配?

我尝试了单个ts_vector和3个提到的列,但我无法提取有关搜索结果的更多详细信息。我应该以某种方式将全文与pg_trgm函数结合起来吗?

1 个答案:

答案 0 :(得分:0)

我认为您可以使用trigram相似性来获得有关匹配类型和所涉及列的确切信息。

我做了一个简单的SQL示例作为演示:

SELECT "first_name", "last_name", "description",
       CASE
           WHEN SIMILARITY("first_name", 'ohns') >= 1.0 THEN 'exact'
           WHEN SIMILARITY("first_name", 'ohns') > 0.0 THEN 'partial'
           ELSE 'no'
       END AS "first_name_match",
       CASE
           WHEN SIMILARITY("last_name", 'ohns') >= 1.0 THEN 'exact'
           WHEN SIMILARITY("last_name", 'ohns') > 0.0 THEN 'partial'
           ELSE 'no'
       END AS "last_name_match",
       CASE
           WHEN SIMILARITY("description", 'ohns') >= 1.0 THEN 'exact'
           WHEN SIMILARITY("description", 'ohns') > 0.0 THEN 'partial'
           ELSE 'no'
       END AS "description_match"
FROM (VALUES
     ('Andy', 'Johnson', 'blah blah blah'),
     ('Andress', 'Bush', 'blah blah'),
     ('Ohns', 'Johnson', 'blah')
) AS I("first_name", "last_name", "description")
WHERE (SIMILARITY("first_name", 'ohns') + SIMILARITY("last_name", 'ohns') + SIMILARITY("description", 'ohns')) > 0.0

 first_name | last_name |  description   | first_name_match | last_name_match | description_match 
------------+-----------+----------------+------------------+-----------------+-------------------
 Andy       | Johnson   | blah blah blah | no               | partial         | no
 Ohns       | Johnson   | blah           | exact            | partial         | no

您可以在此处查看SQL:

http://sqlfiddle.com/#!17/9eecb/6356