2

我有由表格组成的物业管理应用程序:

tenants
landlords
units
properties
vendors-contacts

基本上,我想要一个搜索字段来搜索所有内容,而不必选择我正在搜索的类别。这会是一个可接受的解决方案(技术方面吗?)

从长远来看,跨 5 个表进行搜索是否可以,并且不会让服务器陷入困境?实现这一目标的最佳方法是什么?

使用 PostgreSQL

4

4 回答 4

7

为什么不创建一个视图,它是将要搜索的列聚合为一个的表的联合,然后在该聚合列上进行搜索?

你可以这样做:

select 'tenants:' + ltrim(str(t.Id)), <shared fields> from Tenants as t union
select 'landlords:' + ltrim(str(l.Id)), <shared fields> from Tenants as l union
...

这需要从客户端查询中嵌入一些逻辑;它必须知道如何制造它正在寻找的密钥才能在单个字段上进行搜索。

也就是说,如果您只有一个包含“类型”值(例如,房东、租户)的单独列,然后对类型和 ID 进行过滤,这可能会更好,因为它的计算成本会更低(并且可以更好地优化)。

于 2009-06-29T16:42:14.757 回答
4

您想使用内置的全文搜索或像Lucene这样的单独产品。这针对异构数据的非结构化搜索进行了优化。

另外,不要忘记普通索引不能用于something LIKE '%...%'. 使用全文搜索引擎也将能够进行有效的子字符串搜索。

于 2009-06-29T16:43:21.013 回答
3

I would suggest using a specialized full-text indexing tool like Lucene for this. It will probably be easier to get up and running, and the result is faster and more featureful too. Postgres full text indexes will be useful if you also need structured search capability on top of this or transactionality of your search index is important.

If you do want to implement this in the database, something like the following scheme might work, assuming you use surrogate keys:

  1. for each searchable table create a view that has the primary key column of that table, the name of the table and a concatenation of all the searchable fields in that table.
  2. create a functional GIN or GiST index on the underlying over the to_tsvector() of the exact same concatenation.
  3. create a UNION ALL over all the views to create the searchable view.

After that you can do the searches like this:

SELECT id, table_name, ts_rank_cd(body, query) AS rank
    FROM search_view, to_tsquery('search&words') query
    WHERE query @@ body
    ORDER BY rank DESC
    LIMIT 10;
于 2009-06-29T17:31:09.727 回答
1

你应该没问题,而且真的没有其他好的(简单)方法可以做到这一点。只需确保您正在搜索的字段已正确编入索引。

于 2009-06-29T16:42:44.540 回答