欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL2005CLR函数扩展 - 关于山寨索引

程序员文章站 2023-10-31 10:04:40
本文只是一个山寨试验品,思路仅供参考. ------------------------------------------------------------------...
本文只是一个山寨试验品,思路仅供参考.
--------------------------------------------------------------------------------
原理介绍:
索引建立
目录结构划分方案也只是很简易的实现了一下,通过unicode把任意连续的两个字符(中文或英文)分为4个字节来做四层目录,把索引的内容对应的主关键字(主要为了使用sql索引和唯一性)作为文件名,两个字符在索引内容中的位置作为文件后缀来存储.文件本身为0字节,不保存任何信息.

比如一条数据 "pk001","山寨索引"
山寨索引 四个字的unicode为
[0]: 113
[1]: 92
[2]: 232
[3]: 91
[4]: 34
[5]: 125
[6]: 21
[7]: 95
那么对应的文件结构为
../113/92/232/91/pk001 .0
../232/91/34/125/pk001 .1
../34/125/21/95/pk001 .2

索引使用
比如搜索"寨索引 "
则搜索 "../232/91/34/125/" 目录下的所有文件,然后根据 pk001 .1的文件后缀名1,去看 ../34/125/21/95/pk001.2文件是否存在.依次类推,最后返回一个结果集.
--------------------------------------------------------------------------------
实用性
具体的实用性还有待验证.这只是实现了精确的like搜索,而不能做常见搜索引擎的分词效果.另外海量数据重建索引的性能也是面临很严峻的问题,比如cpu负载和磁盘io负载.关于windows一个目录下可以保持多少个文件而不会对文件搜索造成大的性能损失也有待评估,不过这个可以考虑根据主键的文件名hash来增加文件目录深度降低单一目录下的文件数量.
--------------------------------------------------------------------------------
演示效果
实现了针对test标的name和caption两个字段作索引搜索.
 
-- 设置和获取索引文件根目录
--select dbo.xfn_setmyindexfileroot('d:/myindex')
--select dbo.xfn_getmyindexfileroot()
-- 建立测试环境
 go
create table test( id uniqueidentifier , name nvarchar ( 100), caption nvarchar ( 100))
insert into test select top 3 newid (), ' 我的索引 ' , ' 测试 ' from sysobjects
insert into test select top 3 newid (), ' 我的测试 ' , ' 索引 ' from sysobjects
insert into test select top 3 newid (), ' 测试索引 ' , ' 测试索引 ' from sysobjects
insert into test select top 3 newid (), ' 我的索引 ' , ' 索引 ' from sysobjects
create index i_testid on test( id)
-- 建立索引文件
declare @t int
select @t=
dbo. xfn_setkeyformyindex( id, 'testindex' , name + ' ' + caption)   
from test
-- 查询数据
select  a.*   from   test a, dbo. xfn_getkeyfrommyindex( '测试 索引 我的' , 'testindex' )  b
    where a. id= b. pk
/*
0c4634ea-df94-419a-a8e5-793bd5f54eed   我的索引 测试
2dd87b38-cd3f-4f14-bb4a-00678463898f   我的索引 测试
8c67a6c3-753f-474c-97ba-ce85a2455e3e   我的索引 测试
c9706bf1-fb1f-42fb-8a48-69ec37ead3e5   我的测试 索引
8bbf25cc-9dbb-4fcb-b2eb-d318e587dd5f   我的测试 索引
8b45322d-8e46-4691-961a-cd0078f1fa0a   我的测试 索引
*/
--drop table test
--------------------------------------------------------------------------------
clr代码如下:编译为myfullindex.dll
复制代码 代码如下:

using system;
using system.data.sqltypes;
using microsoft.sqlserver.server;
using system.collections;
using system.collections.generic;
public partial class userdefinedfunctions
{
    /// <summary>
    /// 设置索引目录
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    [microsoft.sqlserver.server.sqlfunction ]
    public static sqlboolean setroot(sqlstring value)
    {
        if (value.isnull) return false ;
        if (system.io.directory .exists(value.value))
        {
            root = value.value;
            return true ;
        }
        else
        {
            return false ;
        }
    }
    /// <summary>
    /// 获取索引目录
    /// </summary>
    /// <returns></returns>
    [microsoft.sqlserver.server.sqlfunction ]
    public static sqlstring getroot()
    {
        return new sqlstring (root);
    }
    /// <summary>
    /// 建立索引
    /// </summary>
    /// <param name="key"> 主键 </param>
    /// <param name="indexname"> 索引名称 </param>
    /// <param name="content"> 索引内容 </param>
    /// <returns></returns>
    [microsoft.sqlserver.server.sqlfunction ]
    public static sqlint32 setindex(sqlstring key,sqlstring indexname,sqlstring content)
    {
        if (key.isnull || content.isnull||indexname.isnull) return 0;
        return _setindex(key.value,indexname.value, content.value);
    }

    /// <summary>
    /// 查询索引
    /// </summary>
    /// <param name="word"> 关键字(空格区分) </param>
    /// <param name="indexname"> 索引名称 </param>
    /// <returns></returns>
    [sqlfunction (tabledefinition = "pk nvarchar(900)" , name = "getindex" , fillrowmethodname = "fillrow" )]
    public static ienumerable getindex(sqlstring word,sqlstring indexname)
    {

        system.collections.generic.list <string > ret = new list <string >();
        if (word.isnull || indexname.isnull) return ret;
        return _getindex2(word.value, indexname.value);
    }

    public static void fillrow(object obj, out sqlstring pk)
    {
        string key = obj.tostring();
        pk = key;
    }
    static string root = @"d:/index" ;

    /// <summary>
    /// 获取有空格分隔的索引信息
    /// </summary>
    /// <param name="word"></param>
    /// <param name="indexname"></param>
    /// <returns></returns>
    static system.collections.generic.list <string > _getindex2(string word, string indexname)
    {
        string [] arrword = word.split(new char [] { ' ' }, stringsplitoptions .removeemptyentries);

        system.collections.generic.list <string > key_0 = _getindex(arrword[0], indexname);

        if (arrword.length == 0) return key_0;
        system.collections.generic.list <string > [] key_list=new list <string >[arrword.length-1];
        for (int i = 0; i < arrword.length-1; i++)
        {
            system.collections.generic.list <string > key_i = _getindex(arrword[i+1],indexname);
            key_list[i] = key_i;
        }

        for (int i=key_0.count-1;i>=0;i--)
        {
            foreach (system.collections.generic.list <string > key_i in key_list)
            {
                if (key_i.contains(key_0[i]) == false )
                {
                    key_0.removeat(i);
                    continue ;
                }
            }
        }
        return key_0;
    }
    /// <summary>
    /// 获取单个词的索引信息
    /// </summary>
    /// <param name="word"></param>
    /// <param name="indexname"></param>
    /// <returns></returns>
    static system.collections.generic.list <string > _getindex(string word, string indexname)
    {
        system.collections.generic.list <string > ret = new list <string >();
        byte [] bword = system.text.encoding .unicode.getbytes(word);
        if (bword.length < 4) return ret;

        string path = string .format(@"{0}/{1}/{2}/{3}/{4}/{5}/" , root,indexname, bword[0], bword[1], bword[2], bword[3]);
        if (system.io.directory .exists(path) == false )
        {
            return ret;
        }
        string [] arrfiles = system.io.directory .getfiles(path);

        foreach (string file in arrfiles)
        {
            string key = system.io.path .getfilenamewithoutextension(file);
            string index = system.io.path .getextension(file).trimstart(new char [] { '.' });
            int cindex = int .parse(index);
            bool bhas = true ;
            for (int i = 2; i < bword.length - 3; i = i + 2)
            {
                string nextfile = string .format(@"{0}/{1}/{2}/{3}/{4}/{5}/{6}.{7}" ,
                    root, indexname, bword[i + 0], bword[i + 1], bword[i + 2], bword[i + 3], key, ++cindex);

                if (system.io.file .exists(nextfile) == false )
                {
                    bhas = false ;
                    break ;
                }
            }
            if (bhas == true &&ret.contains(key)==false )
                ret.add(key);

        }
        return ret;
    }

    /// <summary>
    /// 建立索引文件
    /// </summary>
    /// <param name="key"></param>
    /// <param name="indexname"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    static int _setindex(string key,string indexname, string content)
    {
        byte [] bcontent = system.text.encoding .unicode.getbytes(content);
        if (bcontent.length <= 4) return 0;
        for (int i = 0; i < bcontent.length - 3; i = i + 2)
        {
            string path = string .format(@"{0}/{1}/{2}/{3}/{4}/{5}/" , root,indexname, bcontent[i + 0], bcontent[i + 1], bcontent[i + 2], bcontent[i + 3]);
            if (system.io.directory .exists(path) == false )
            {
                system.io.directory .createdirectory(path);
            }
            string file = string .format(@"{0}/{1}.{2}" , path, key, i / 2);

            if (system.io.file .exists(file) == false )
            {
                system.io.file .create(file).close();
            }
        }
        return content.length;
    }
};

--------------------------------------------------------------------------------
部署的sql脚本如下
--drop function dbo.xfn_setmyindexfileroot
--drop function dbo.xfn_getmyindexfileroot
--drop function dbo.xfn_getkeyfrommyindex
--drop function dbo.xfn_setkeyformyindex
--drop assembly myfullindex
--go
create assembly myfullindex from 'd:/sqlclr/myfullindex.dll' with permission_set = unsafe;
--
go
-- 索引搜索
create function dbo. xfn_getkeyfrommyindex ( @word nvarchar ( max ), @indexname  nvarchar ( 900))   
returns table ( pk nvarchar ( 100))
as external name myfullindex. userdefinedfunctions. getindex
go
-- 索引建立
create function dbo. xfn_setkeyformyindex ( @pk nvarchar ( 900), @indexname  nvarchar ( 900), @word nvarchar ( max ))   
returns int
as external name myfullindex. userdefinedfunctions. setindex
go
-- 获取索引文件根目录
create function dbo. xfn_getmyindexfileroot ()   
returns nvarchar ( max )
as external name myfullindex. userdefinedfunctions. getroot
go
-- 设置索引文件根目录(默认目录为 d:/myindex )
create function dbo. xfn_setmyindexfileroot ( @fileroot nvarchar ( max ))   
returns bit
as external name myfullindex. userdefinedfunctions. setroot
go