我有由表格组成的物业管理应用程序:
tenants
landlords
units
properties
vendors-contacts
基本上,我想要一个搜索字段来搜索所有内容,而不必选择我正在搜索的类别。这会是一个可接受的解决方案(技术方面吗?)
从长远来看,跨 5 个表进行搜索是否可以,并且不会让服务器陷入困境?实现这一目标的最佳方法是什么?
使用 PostgreSQL
我有由表格组成的物业管理应用程序:
tenants
landlords
units
properties
vendors-contacts
基本上,我想要一个搜索字段来搜索所有内容,而不必选择我正在搜索的类别。这会是一个可接受的解决方案(技术方面吗?)
从长远来看,跨 5 个表进行搜索是否可以,并且不会让服务器陷入困境?实现这一目标的最佳方法是什么?
使用 PostgreSQL
为什么不创建一个视图,它是将要搜索的列聚合为一个的表的联合,然后在该聚合列上进行搜索?
你可以这样做:
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 进行过滤,这可能会更好,因为它的计算成本会更低(并且可以更好地优化)。
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:
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;
你应该没问题,而且真的没有其他好的(简单)方法可以做到这一点。只需确保您正在搜索的字段已正确编入索引。