使用postgreSQL+bamboo搭建比lucene方便N倍的全文搜索
所有用到到包有:
cmake-2.6.4.tar.gz (编nlpbamboo用)
CRF++-0.53.tar.gz(同上)
nlpbamboo-1.1.1.tar.bz2(分词用)
postgreSQL-8.3.3.tar.gz(索引用)
安装pgsql
tar -zxvf postgreSQL-8.3.3.tar.gz
cd postgre-8.3.3
./configure –prefix=/opt/pgsql
make
make install
useradd postgre
chown -R postgre.postgre /opt/pgsql
su – postgre
vi ~postgre/.bash_profile
添加
export PATH
PGLIB=/opt/pgsql/lib
PGDATA=/data/PGSearch
PATH=$PATH:/opt/pgsql/bin
MANPATH=$MANPATH:/opt/pgsql/man
export PGLIB PGDATA PATH MANPATH
# mkdir -p /data/PGSearch
# chown -R postgre.postgre /data/PGSearch
# chown -R postgre.postgre /opt/pgsql
#sudo -u postgre /opt/pgsql/bin/initdb –locale=zh_CN.UTF-8 –encoding=utf8 -D /data/PGSearch
#sudo -u postgre /opt/pgsql/bin/postmaster -i -D /data/PGSearch & //允许网络访问
#sudo -u postgre /opt/pgsql/bin/createdb kxgroup
# vim /data/PGSearch/pg_hba.conf 如下增加可访问的机器: www.2cto.com
host all all 10.2.19.178 255.255.255.0 trust
#su – postgre
$pg_ctl stop
$postmaster -i -D /data/PGSearch &
安装中文分词(Cmake CRF++ bamboo)
Cmake是为了编译bamboo,CRF++是bamboo依赖的。
tar -zxvf cmake-2.6.4.tar.gz
cd cmake-2.6.4
./configure
gmake
make install
tar -zxvf CRF++-0.53.tar.gz
cd CRF++-0.53
./configure
make
make install
tar -jxvf nlpbamboo-1.1.1.tar.bz2
cd nlpbamboo-1.1.1
mkdir build
cd build/
cmake .. -DCMAKE_BUILD_TYPE=release
make all
make install
cp index.tar.bz2 /opt/bamboo/
cd /opt/bamboo/
tar -jxvf index.tar.bz2
#/opt/bamboo/bin/bamboo
如果出现:
ERROR: libcrfpp.so.0: cannot open shared object file: No such file or directory
就执行:
ln -s /usr/local/lib/libcrfpp.so.* /usr/lib/
ldconfig
增加上中文分词扩展到pgsql
#vim /root/.bash_profile 也增加:
PGLIB=/opt/pgsql/lib
PGDATA=/data/PGSearch
PATH=$PATH:/opt/pgsql/bin
MANPATH=$MANPATH:/opt/pgsql/man
export PGLIB PGDATA PATH MANPATH
#source ~/.bash_profile
cd /opt/bamboo/exts/postgres/chinese_parser/
make
make install
su – postgre
cd /opt/pgsql/share/contrib/
touch /opt/pgsql/share/tsearch_data/chinese_utf8.stop
psql kxgroup
\i chinese_parser.sql 导入
再执行下面的sql,已经可以将一段话分词了:
SELECT to_tsvector(’chinesecfg’, ‘结果在命令行下执行bamboo才知道’);
先到这里,下一部分讲述对TEXT字段进行索引和查询,完整构造一整个搜索引擎。
www.2cto.com
一、基础篇
本回从一条sql开始:
select * from dbname where field_name @@ ‘aa|bb’ order by rank(field_name, ‘aa|bb’);
从这个sql字面意思讲解:从 dbname这个表中查field_name匹配aa或者是bb的词,并且按照他们的匹配的RANK排序。
基本上明白上面这段话后,来学习四个概念:tsvector、 tsquery、 @@ 、gin。
1.tsvector:
在postgreSQL 8.3自带支持全文检索功能,在之前的版本中需要安装配置tsearch2才能使用。它提供两个数据类型(tsvector,tsquery),并且通过 动态检索自然语言文档的集合,定位到最匹配的查询结果,tsvector正是其中之一。
一个tsvector的值是唯一分词的分类列表,把一话一句词格式化为不同的词条,在进行分词处理的时候,tsvector会自动去掉分词中重复的词条,按照一定的顺序装入。例如
SELECT ‘a fat cat sat on a mat and ate a fat rat’::tsvector;
tsvector
—————————————————-
‘a’ ‘on’ ‘and’ ‘ate’ ‘cat’ ‘fat’ ‘mat’ ‘rat’ ’sat’
通过tsvector把一个字符串按照空格进行分词,这可以把分词后的词按照出现的次数排成一排(还会按词长度)。
对于英文和中文的全文检索我们还要看下面这条sql:
SELECT to_tsvector(’english’, ‘The Fat Rats’);
to_tsvector
—————–
‘fat’:2 ‘rat’:3
to_tsvector函数来是tsvector规格化的,在其中可指定所使用的分词。
2.tsquery:
顾名思义,tsquery,表示的应该是查询相关的