美文网首页
postgresql全文检索 tsvector类型使用

postgresql全文检索 tsvector类型使用

作者: raysonfang | 来源:发表于2018-10-08 11:26 被阅读251次

    一, 介绍
    数据库树形结构存储是必须的, 也是用得比较多的地方, 如何才能更好的快速搜索呢?

    二, 构建步骤
    数据库字段: 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)
    

    相关文章

      网友评论

          本文标题:postgresql全文检索 tsvector类型使用

          本文链接:https://www.haomeiwen.com/subject/eivdaftx.html