4

我在 Postgres 中解析 url 时遇到问题。我有一个充满客户和与他们相关联的网址的数据库。我需要一组与每个客户关联的唯一域。我希望能够在查询中进行解析,而不是将结果转储到 Python 并在那里解析。

在 postgres 文档中,我发现了这一点,但不知道如何将其合并到我的查询中:

SELECT alias, description, token FROM ts_debug('http://example.com/stuff/index.html');  

  alias   |  description  |            token               
----------+---------------+------------------------------  
 protocol | Protocol head | http://  
 url      | URL           | example.com/stuff/index.html  
 host     | Host          | example.com  
 url_path | URL path      | /stuff/index.html  

http://www.postgresql.org/docs/9.3/static/textsearch-parsers.html

我从一张桌子开始,像这样:

customer_id | url 
-------------+--------------------   
000001      | www.example.com/fish  
000001      | www.example.com/potato  
000001      | www.potato.com/artichoke
000002      | www.otherexample.com

到目前为止我的代码:

SELECT customer_id, array_agg(url)
FROM customer_url_table
GROUP BY customer_id

这给了我:

customer_id | unique_domains
-----------------------------
000001      | {www.example.com/fish, www.example.com/potato, www.potato.com/greenery}
000002      | {www.otherexample.com}

我想要这样的表:

customer_id | unique_domains
-----------------------------
000001      | {example.com, potato.com}
000002      | {otherexample.com}

使用 AWS 上的 PostgreSQL 9.3.3 数据库。

4

1 回答 1

4

您在上面链接的文档用于Postgres 文本搜索解析器。这需要单独的配置来设置,并且可能比您正在寻找的开销更大和/或不同类型的东西。

如果您确实想走这条路,设置文本解析器,您可以在此处找到更多信息:

http://www.postgresql.org/docs/9.3/static/sql-createtsconfig.html

但是,如果您想在Postgres中进行内联解析,我建议您使用程序化Postgres语言,您可以在其中导入该语言的解析库。

您提到了Python,因此您可以使用PL/Python和 url 解析库,例如urlparse (在 Python 3 中称为urllib.parse )。

有关urlparse 的更多信息

这包括此示例代码:

>>> from urlparse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
>>> o   
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            params='', query='', fragment='')
>>> o.scheme
'http'
>>> o.port
80
>>> o.geturl()
'http://www.cwi.nl:80/%7Eguido/Python.html'

超越该示例,您可以使用主机名成员获取主机

>>> print o.hostname
www.cwi.nl

如果您只想正确解析域名(有很多边缘情况和变体 - 即减去www和可能存在的任何其他分类部分 -最好采用this answer中的方法。

有关设置PL/Python的更多信息,您可以访问此处:

http://www.postgresql.org/docs/9.3/static/plpython.html

所以,这就是你可以在Postgres中进行解析的方式

而不是将我的结果转储到 Python 并在那里解析

它最终与PL/Python有点绕圈子,但如果你真的想在 SQL 中进行解析(特别是出于性能原因,比如跨大型数据集),使用PL/Python可能值得额外努力。

于 2014-07-24T00:20:09.240 回答