一, 介绍
数据库树形结构存储是必须的, 也是用得比较多的地方, 如何才能更好的快速搜索呢?
二, 构建步骤
数据库字段: id, pid, path, ssi(tsvector)
Java代码:
if(o.getPid().intValue() == 0){
o.setLevel(0);
o.setPath(o.getId() + ".");
}else{
String path = "";
if(o.getPath() != null && o.getPath().endsWith(".")){
path = o.getPath()+o.getId()+".";
}else{
path = o.getPath()+"."+o.getId()+".";
}
o.setPath(path);
}
数据库触发器创建
DECLARE rec RECORD; ssi_path VARCHAR; pos INTEGER; tmp_ssi tsvector;
BEGIN
IF (NEW.path IS NOT NULL)
THEN
ssi_path:=NEW.path;
LOOP
-- index := position('.' in ssi_path);
-- RAISE EXCEPTION 'ssi_path:%',ssi_path;
pos := public.last_index(ssi_path,'.');
-- RAISE EXCEPTION 'pos:%',pos;
IF (pos > 0)
THEN
-- ssi_path := substr(ssi_path,1, length(ssi_path)-1);
ssi_path := substr(ssi_path,1, pos-1);
-- RAISE EXCEPTION 'ssi_path:%',ssi_path;
tmp_ssi := coalesce(tmp_ssi,'')||to_tsvector( coalesce(ssi_path,''));
-- RAISE EXCEPTION 'tmp_ssi:%',tmp_ssi;
END IF;
EXIT WHEN (pos = 0);
END LOOP;
NEW.ssi:=tmp_ssi;
END IF;
RETURN NEW;
END;
快速查询 -- 查找自身及子节点
SELECT *
FROM public.organization where ssi @@ to_tsquery(path)