使用NoSQL实现高并发CRM系统实践(源代码+解析)

前端之家收集整理的这篇文章主要介绍了使用NoSQL实现高并发CRM系统实践(源代码+解析)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

又想速度快,又要大数据,又要保证数据不出错,还要拥抱变化,改需求的时候不那么痛苦,特别是字段的调整,按照以前的做法,想想就头疼。使用Nosql,简直就是随心所欲,再奇葩的数据结构,处理起来也很容易。下面看我如何用Nosql数据库实现高并发,高可靠的CRM系统。

1、前言

随着facebook、微博等WEB2.0互联网网站的兴起,传统的关系数据库在应付web2.0网站,特别是超大规模和高并发的SNS类型的web2.0纯动态网站已经显得力不从心,暴露了很多难以克服的问题,而非关系型的数据库则由于其本身的特点得到了非常迅速的发展。

Nosql项目的名字上看不出什么相同之处,但是,它们通常在某些方面相同:它们可以处理超大量的数据。

目前Nosql数据库的发展非常迅速,各大公司都在大量使用,比如GOOGLE、360、百度,在不久的将来必将成为主流。

为了适应大数据处理的需要,在将来较长的一段时间里能够让系统适应高并发的访问,我们在开发CRM系统的过程中,经过不断摸索和实践,通过使用Nosql数据库解决了传统关系型数据很难解决的难题,实现了大数据和高并发的处理能力。

2、系统展示

3、性能数据

测试环境是CentOS系统,ngnix + PHP5.0, i7 2600K处理器,8G内存,SSDB 1.6.8.8版本。

针对最常用的功能,以前数据量最大的功能进行测试。

PHP程序模拟UI层直接调用业务逻辑接口,插入大量数据,并对大量数据进行读取。

功能

测试说明

测试结果(毫秒)

添加客户资料

添加100万条数据

15203

客户资料查询

100万条客户资料进行查询1万次

20

下订单

添加100万条数据

58653

订单查询

100万条订单进行查询1万次

25

添加新消息

添加100万条数据

13454

获取新消息

100万条消息数据进行查询1万次

18

4、系统架构

在使用数据库的选择上,我们使用同时具有高性能,并且接口使用很简单的SSDB。因为SSDB的作者是我的朋友,同时SSDB已经在百度、360等大公司大量应用,所以不用担心可靠性问题。

开发语言使用PHP

4.1 系统需求

2014年禾葡兰借着微信营销的大好机会,在几个月时间里,团队发展到了100人以上,每日订单数超过200单。

快速发展的过程中,对于数据处理的需求日益增长,通过数据和统计进行决策,使经营水平和收入更上一个台阶,并能够适应将来的大规模扩展的需要。

目前纯手工统计和计算比较容易出错,而且效率很低,很难适应快速增长的需要,为了解决这些问题,欣所罗门核心团队成员一致认为有必要开发一个软件系统来解决问题。

4.2 需要解决的3大难点

1、事务处理

在数据完整性要求很高的CRM系统中,必需要事务处理机制,保证原子操作。但是,Nosql数据库最大的缺点就是不支持事务处理。

要想实现事务处理,目前最好的方法是使用zookeeper,可以模拟实现分布式事务。

2、数据关系

和关系数据库不同的是,SSDB没有关系的概念。所有数据间的关系必需在开始的时候设计好。

3、组合条件查询

由于Nosql数据库没有模式,因此,想要根据数据内容里的某个字段对数据集进行筛选,根本不可能。所以,我们使用lucene实现全文索引,解决了组合条件查询的问题。

4.3 系统设计

由于目前流行的PHP开发框架MVC框架都不支持Nosql数据,同时避免由于开源框架带来的安全问题,因此不使用MVC框架。仅在UI层使用PHP的smarty模板引擎。

系统统一入口文件index.PHP,通过m参数引用ui目录和controller目录下相应的文件

代码目录结构

/ CRM系统根目录

/index.PHP (统一入口文件)

|-------common/ (用于存放公共函数)

|--------common.PHP (公共函数接口文件,使用公共函数只需要引用一个文件就可以。)

|-------config/ (用于存放配置信息)

|-------model/ (数据对像)

|-------data/ (数据层,对数据的读写封装。)

|-------controller/ (业务逻辑层)

|-------ui/ (smarty引擎和模板)

|-------libs/ (smarty引擎目录)

|-------configs/ (smarty引擎配置文件目录)

|-------plugins/ (smarty引擎自定义的一些实用插件目录)

|-------templates/ (smarty引擎模板目录)

|-------templates_c/ (smarty引擎模板编译目录)

|-------cache/ (smarty缓存目录)

5、涉及内容

一、 数据库连接

二、 自动编号ID实现

三、数据的读写

四、 数据关系实现

五、 分布式事务实现

六、 全文索引

七、 组合条件查询

6、源码解析

一、数据库连接

SSDB的数据库连接很简单。

  1. include_once('SSDB.PHP');
  2. try{
  3. $ssdb=newSimpleSSDB('127.0.0.1',8888);
  4. }catch(SSDBException$e){
  5. die(__LINE__.''.$e->getMessage());
  6. }
  1. include_once('SSDB.PHP');
  2. try{
  3. $ssdb=newSimpleSSDB('127.0.0.1',8888);
  4. }catch(SSDBException$e){
  5. die(__LINE__.''.$e->getMessage());
  6. }


二、 自动编号ID实现

一般来说,我们在进行数据设计的时候,都会给每条记录设置一个自动编号的ID。但是在Nosql数据中,需要自己来实现自动编号ID。

我们通过SSDB的incr接口,就可以模拟自动编号ID的实现。

系统初始化的时候,我们在数据库增加一条数据。

  1. $ssdb->set('hpl_product_autoincrement_id',0);
  1. $ssdb->set('hpl_product_autoincrement_id',0);


添加新记录的时候,使用incr接口得到新的自动编号ID,由于incr接口是原子操作,所以不会出现重复的ID。

  1. $id=$ssdb->incr('hpl_product_autoincrement_id',1);
  1. $id=$ssdb->incr('hpl_product_autoincrement_id',1);


三、 数据的读写

首先,我们要创建数据的model类。下面是产品model类。

  1. classProductModel{
  2. public$id;//编号
  3. public$catalogid;//所属分类
  4. public$name;//产品名称
  5. public$cost;//产品成本价格
  6. public$price;//销售价格
  7. public$saleprice;//优惠价格
  8. public$amount;//产品数量
  9. public$facetype;//适合皮肤类型
  10. public$desc;//产品描述
  11. public$code;//产品编号
  12. public$weight;//净含量(克)
  13. public$effect;//主要功效
  14. public$crowd;//适合人群
  15. public$addtime;//产品添加时间
  16. public$status;//产品状态(0=下架1=上架)
  17. }
  1. classProductModel{
  2. public$id; //编号
  3. public$catalogid; //所属分类
  4. public$name; //产品名称
  5. public$cost; //产品成本价格
  6. public$price; //销售价格
  7. public$saleprice; //优惠价格
  8. public$amount; //产品数量
  9. public$facetype; //适合皮肤类型
  10. public$desc; //产品描述
  11. public$code; //产品编号
  12. public$weight; //净含量(克)
  13. public$effect; //主要功效
  14. public$crowd; //适合人群
  15. public$addtime; //产品添加时间
  16. public$status; //产品状态(0=下架1=上架)
  17. }

添加记录

  1. $product=newProductModel();
  2. $product->id=$id;
  3.  
  4. ...
  5.  
  6. $key='hpl_product_'.$id;
  7. $json=json_encode($product);
  8. $ssdb->hset('hpl_product',$key,$json);
  1. $product=newProductModel();
  2. $product->id=$id;
  3.  
  4. ...
  5.  
  6. $key='hpl_product_'.$id;
  7. $json=json_encode($product);
  8. $ssdb->hset('hpl_product',$json);

增加索引,根据产品ID进行索引,在使用数据的时候就可以根据产品ID获取数据列表(如果有多种排列方式就需要创建多个索引)。

  1. $key='hpl_product_'.$id;
  2. $ssdb->zset('hpl_product_id',$id);
  1. $key='hpl_product_'.$id;
  2. $ssdb->zset('hpl_product_id',$id);


根据索引获取产品列表(前10个)。

  1. $products=array();
  2. //根据索引取出产品列表
  3. $items=$ssdb->zscan('hpl_product_id','',10);
  4. foreach($itemsas$key=>$score){
  5. //取出产品信息
  6. $json=$ssdb->hget('hpl_product',$key);
  7. $products[]=json_decode($json);
  8. }

四、数据关系实现

添加产品的时候,需要把产品和产品分类关联起来,可以根据产品分类列出产品。使用SSDB我们只需要对每个产品分类创建一个列表就可以了。

添加关系,在列表里添加一条数据。

  1. $hname='hpl_product_catalog_'.$catalogid;
  2. $hkey='hpl_product_'.$id;
  3. $ssdb->hset($hname,$hkey,$id);
  1. $hname='hpl_product_catalog_'.$catalogid;
  2. $hkey='hpl_product_'.$id;
  3. $ssdb->hset($hname,$id);


删除关系,当改变产品分类或者删除产品的时候执行。

  1. $hname='hpl_product_catalog_'.$catalogid;
  2. $hkey='hpl_product_'.$id;
  3. $ssdb->hdel($hname,$hkey);
  1. $hname='hpl_product_catalog_'.$catalogid;
  2. $hkey='hpl_product_'.$id;
  3. $ssdb->hdel($hname,$hkey);

根据分类取出产品列表(前10个)。

  1. $products=array();
  2. //根据分类取出产品列表
  3. $hname='hpl_product_catalog_'.$catalogid;
  4. $keys=$ssdb->hkeys($hname,10);
  5. foreach($keysas$key){
  6. //取出产品信息
  7. $json=$ssdb->hget('hpl_product',$key);
  8. $products[]=json_decode($json);
  9. }
  1. $products=array();
  2. //根据分类取出产品列表
  3. $hname='hpl_product_catalog_'.$catalogid;
  4. $keys=$ssdb->hkeys($hname,$key);
  5. $products[]=json_decode($json);
  6. }


五、分布式事务实现

由于CRM系统对数据统一性的需要,所以必需要有事务来支持。比如在下订单的时候,如果没有事务,在并发处理时就有可能导致产品库存出错。由于SSDB数据库没有实现事务处理,我们使用zookeeper来实现分布式锁的处理,保证关键业务的原子操作。

事务处理的实现我们分别由前台后台实现,前台系统发送业务处理请求,后台进程收到消息后进行处理,后台进程处理结束后设置处理标志,前台系统每隔一段时间查询一次标志位,检查业务是否处理完成。

后台实现使用JAVA语言编写。

  1. /**
  2. Executor.java
  3. */
  4. importjava.io.FileOutputStream;
  5. importjava.io.IOException;
  6. importjava.io.InputStream;
  7. importjava.io.OutputStream;
  8.  
  9. importorg.apache.zookeeper.KeeperException;
  10. importorg.apache.zookeeper.WatchedEvent;
  11. importorg.apache.zookeeper.Watcher;
  12. importorg.apache.zookeeper.ZooKeeper;
  13.  
  14. publicclassExecutor
  15. implementsWatcher,Runnable,DataMonitor.DataMonitorListener
  16. {
  17. Stringznode;
  18.  
  19. DataMonitordm;
  20.  
  21. ZooKeeperzk;
  22.  
  23. Stringfilename;
  24.  
  25. Stringexec[];
  26.  
  27. Processchild;
  28.  
  29. publicExecutor(StringhostPort,Stringznode,Stringfilename,Stringexec[])throwsKeeperException,IOException{
  30. this.filename=filename;
  31. this.exec=exec;
  32. zk=newZooKeeper(hostPort,3000,this);
  33. dm=newDataMonitor(zk,znode,null,this);
  34. }
  35.  
  36. /**
  37. *@paramargs
  38. */
  39. publicstaticvoidmain(String[]args){
  40. if(args.length<4){
  41. System.err
  42. .println("USAGE:ExecutorhostPortznodefilenameprogram[args...]");
  43. System.exit(2);
  44. }
  45. StringhostPort=args[0];
  46. Stringznode=args[1];
  47. Stringfilename=args[2];
  48. Stringexec[]=newString[args.length-3];
  49. System.arraycopy(args,3,exec,exec.length);
  50. try{
  51. newExecutor(hostPort,filename,exec).run();
  52. }catch(Exceptione){
  53. e.printStackTrace();
  54. }
  55. }
  56.  
  57. /***************************************************************************
  58. *Wedoprocessanyeventsourselves,wejustneedtoforwardthemon.
  59. *
  60. *@seeorg.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent)
  61. */
  62. publicvoidprocess(WatchedEventevent){
  63. dm.process(event);
  64. }
  65.  
  66. publicvoidrun(){
  67. try{
  68. synchronized(this){
  69. while(!dm.dead){
  70. wait();
  71. }
  72. }
  73. }catch(InterruptedExceptione){
  74. }
  75. }
  76.  
  77. publicvoidclosing(intrc){
  78. synchronized(this){
  79. notifyAll();
  80. }
  81. }
  82.  
  83. staticclassStreamWriterextendsThread{
  84. OutputStreamos;
  85.  
  86. InputStreamis;
  87.  
  88. StreamWriter(InputStreamis,OutputStreamos){
  89. this.is=is;
  90. this.os=os;
  91. start();
  92. }
  93.  
  94. publicvoidrun(){
  95. byteb[]=newbyte[80];
  96. intrc;
  97. try{
  98. while((rc=is.read(b))>0){
  99. os.write(b,rc);
  100. }
  101. }catch(IOExceptione){
  102. }
  103.  
  104. }
  105. }
  106.  
  107. publicvoidexists(byte[]data){
  108. if(data==null){
  109. if(child!=null){
  110. System.out.println("Killingprocess");
  111. child.destroy();
  112. try{
  113. child.waitFor();
  114. }catch(InterruptedExceptione){
  115. }
  116. }
  117. child=null;
  118. }else{
  119. if(child!=null){
  120. System.out.println("Stoppingchild");
  121. child.destroy();
  122. try{
  123. child.waitFor();
  124. }catch(InterruptedExceptione){
  125. e.printStackTrace();
  126. }
  127. }
  128. try{
  129. FileOutputStreamfos=newFileOutputStream(filename);
  130. fos.write(data);
  131. fos.close();
  132. }catch(IOExceptione){
  133. e.printStackTrace();
  134. }
  135. try{
  136. System.out.println("Startingchild");
  137. child=Runtime.getRuntime().exec(exec);
  138. newStreamWriter(child.getInputStream(),System.out);
  139. newStreamWriter(child.getErrorStream(),System.err);
  140. }catch(IOExceptione){
  141. e.printStackTrace();
  142. }
  143. }
  144. }
  145. }
  146.  
  147.  
  148.  
  149. /**
  150. DataMonitor.java
  151. */
  152. importjava.util.Arrays;
  153.  
  154. importorg.apache.zookeeper.KeeperException;
  155. importorg.apache.zookeeper.WatchedEvent;
  156. importorg.apache.zookeeper.Watcher;
  157. importorg.apache.zookeeper.ZooKeeper;
  158. importorg.apache.zookeeper.AsyncCallback.StatCallback;
  159. importorg.apache.zookeeper.KeeperException.Code;
  160. importorg.apache.zookeeper.data.Stat;
  161. importcom.udpwork.ssdb.SSDB;
  162. importcom.udpwork.ssdb.Link;
  163. importcom.udpwork.ssdb.MemoryStream;
  164. importcom.udpwork.ssdb.Response;
  165.  
  166. publicclassDataMonitorimplementsWatcher,StatCallback{
  167.  
  168. ZooKeeperzk;
  169.  
  170. Stringznode;
  171.  
  172. WatcherchainedWatcher;
  173.  
  174. booleandead;
  175.  
  176. DataMonitorListenerlistener;
  177.  
  178. byteprevData[];
  179.  
  180. publicDataMonitor(ZooKeeperzk,WatcherchainedWatcher,DataMonitorListenerlistener){
  181. this.zk=zk;
  182. this.znode=znode;
  183. this.chainedWatcher=chainedWatcher;
  184. this.listener=listener;
  185. //Getthingsstartedbycheckingifthenodeexists.Wearegoing
  186. //tobecompletelyeventdriven
  187. zk.exists(znode,true,this,null);
  188. }
  189.  
  190. /**
  191. *OtherclassesusetheDataMonitorbyimplementingthismethod
  192. */
  193. publicinterfaceDataMonitorListener{
  194. /**
  195. *Theexistencestatusofthenodehaschanged.
  196. */
  197. voidexists(bytedata[]);
  198.  
  199. /**
  200. *TheZooKeepersessionisnolongervalid.
  201. *
  202. *@paramrc
  203. *theZooKeeperreasoncode
  204. */
  205. voidclosing(intrc);
  206. }
  207.  
  208. publicvoidprocess(WatchedEventevent){
  209. Stringpath=event.getPath();
  210. if(event.getType()==Event.EventType.None){
  211. //Wearearebeingtoldthatthestateofthe
  212. //connectionhaschanged
  213. switch(event.getState()){
  214. caseSyncConnected:
  215. //Inthisparticularexamplewedon'tneedtodoanything
  216. //here-watchesareautomaticallyre-registeredwith
  217. //serverandanywatchestriggeredwhiletheclientwas
  218. //disconnectedwillbedelivered(inorderofcourse)
  219. break;
  220. caseExpired:
  221. //It'sallover
  222. dead=true;
  223. listener.closing(KeeperException.Code.SessionExpired);
  224. break;
  225. }
  226. }else{
  227. if(path!=null&&path.equals(znode)){
  228. //Somethinghaschangedonthenode,let'sfindout
  229. //读取订单信息
  230. //znode=/product/order/
  231. ...
  232.  
  233. //计算库存是否充足
  234. ...
  235.  
  236. //生成订单数据
  237. ...
  238.  
  239. //减少产品库存
  240. ...
  241.  
  242. zk.exists(znode,null);
  243. }
  244. }
  245. if(chainedWatcher!=null){
  246. chainedWatcher.process(event);
  247. }
  248. }
  249.  
  250. publicvoidprocessResult(intrc,Stringpath,Objectctx,Statstat){
  251. booleanexists;
  252. switch(rc){
  253. caseCode.Ok:
  254. exists=true;
  255. break;
  256. caseCode.NoNode:
  257. exists=false;
  258. break;
  259. caseCode.SessionExpired:
  260. caseCode.NoAuth:
  261. dead=true;
  262. listener.closing(rc);
  263. return;
  264. default:
  265. //Retryerrors
  266. zk.exists(znode,null);
  267. return;
  268. }
  269.  
  270. byteb[]=null;
  271. if(exists){
  272. try{
  273. b=zk.getData(znode,false,null);
  274. }catch(KeeperExceptione){
  275. //Wedon'tneedtoworryaboutrecoveringnow.Thewatch
  276. //callbackswillkickoffanyexceptionhandling
  277. e.printStackTrace();
  278. }catch(InterruptedExceptione){
  279. return;
  280. }
  281. }
  282. if((b==null&&b!=prevData)
  283. ||(b!=null&&!Arrays.equals(prevData,b))){
  284. listener.exists(b);
  285. prevData=b;
  286. }
  287. }
  288. }

PHP zookeeper处理类

  1. classOrderWorkerextendsZookeeper{
  2.  
  3. constCONTAINER='/product/order';
  4.  
  5. protected$acl=array(
  6. array(
  7. 'perms'=>Zookeeper::PERM_ALL,'scheme'=>'world','id'=>'anyone'));</p><p>private$znode;
  8.  
  9. publicfunction__construct($host='',$watcher_cb=null,$recv_timeout=10000){
  10. parent::__construct($host,$watcher_cb,$recv_timeout);
  11. }
  12.  
  13. //添加订单
  14. publicfunctionAdd($order){
  15. if(!$this->exists(self::CONTAINER)){
  16. $this->create(self::CONTAINER,$this->acl);
  17. }
  18.  
  19. $this->znode=$this->create(self::CONTAINER.'/w-',$this->acl,Zookeeper::EPHEMERAL|Zookeeper::SEQUENCE);
  20.  
  21. $this->set($this->znode,json_encode(array('status'=>0,'data'=>$order,'orderid'=>'')));
  22.  
  23. $this->znode=str_replace(self::CONTAINER.'/',$this->znode);
  24.  
  25. return$this->znode;
  26. }
  27.  
  28. //获取订单处理信息
  29. publicfunctionGet($znode){
  30. $data=$this->get(self::CONTAINER.'/'.$znode);
  31. $json=json_decode($data);
  32. return$json;
  33. }
  34.  
  35. //删除订单znode
  36. publicfunctionDel($znode){
  37. $this->delete(self::CONTAINER.'/'.$znode);
  38. }
  39.  
  40. }
  1. classOrderWorkerextendsZookeeper{
  2.  
  3. constCONTAINER='/product/order';
  4.  
  5. protected$acl=array(
  6. array(
  7. 'perms'=>Zookeeper::PERM_ALL,$this->znode);
  8.  
  9. return$this->znode;
  10. }
  11.  
  12. //获取订单处理信息
  13. publicfunctionGet($znode){
  14. $data=$this->get(self::CONTAINER.'/'.$znode);
  15. $json=json_decode($data);
  16. return$json;
  17. }
  18.  
  19. //删除订单znode
  20. publicfunctionDel($znode){
  21. $this->delete(self::CONTAINER.'/'.$znode);
  22. }
  23.  
  24. }



PHP前台下订单:

  1. $worker=newOrderWorker('127.0.0.1:2181');
  2. $znode=$worker->Add($order);
  3. echojson_encode(array('code'=>0,'znode'=>$znode));
  1. echojson_encode(array('code'=>0,'znode'=>$znode));


PHP前台检测订单:

  1. $worker=newOrderWorker('127.0.0.1:2181');
  2. $data=$worker->Get($znode);
  3. if(intval($data->status)==1)
  4. {
  5. $worker->Del($znode);
  6. echojson_encode(array('status'=>1,'msg'=>'订单处理成功','orderid'=>$data->orderid));
  7. }
  8. elseif(intval($data->status)==2)
  9. {
  10. $worker->Del($znode);
  11. echojson_encode(array('status'=>2,'msg'=>'订单处理失败'));
  12. }
  13. else
  14. {
  15. echojson_encode(array('status'=>0,'msg'=>'正在处理'));
  16. }
  1. $worker=newOrderWorker('127.0.0.1:2181');
  2. $data=$worker->Get($znode);
  3. if(intval($data->status)==1)
  4. {
  5. $worker->Del($znode);
  6. echojson_encode(array('status'=>1,'orderid'=>$data->orderid));
  7. }
  8. elseif(intval($data->status)==2)
  9. {
  10. $worker->Del($znode);
  11. echojson_encode(array('status'=>2,'msg'=>'订单处理失败'));
  12. }
  13. else
  14. {
  15. echojson_encode(array('status'=>0,'msg'=>'正在处理'));
  16. }


六、全文索引

创建索引

  1. importjava.io.File;
  2. importjava.io.FileReader;
  3. importjava.io.IOException;
  4.  
  5. importorg.apache.lucene.analysis.standard.StandardAnalyzer;
  6. importorg.apache.lucene.document.Document;
  7. importorg.apache.lucene.document.Field;
  8. importorg.apache.lucene.document.LongField;
  9. importorg.apache.lucene.document.StringField;
  10. importorg.apache.lucene.document.TextField;
  11. importorg.apache.lucene.index.IndexWriter;
  12. importorg.apache.lucene.index.IndexWriterConfig;
  13. importorg.apache.lucene.store.Directory;
  14. importorg.apache.lucene.store.FSDirectory;
  15. importorg.apache.lucene.util.Version;
  16.  
  17.  
  18. publicclassIndexOrders{
  19.  
  20. privateIndexWriterwriter=null;
  21.  
  22. publicvoidAdd(StringindexPath,OrderModelorder)
  23. throwsIOException{
  24.  
  25. //获取放置索引文件的位置,若传入参数为空,则读取search.properties中设置的默认值。
  26. if(indexPath==null){
  27. indexPath=LoadProperties.getProperties("indexDir");
  28. }
  29. finalFileindexDir=newFile(indexPath);
  30. if(!indexDir.exists()||!indexDir.canRead()){
  31. System.out
  32. .println("Documentdirectory'"
  33. +indexDir.getAbsolutePath()
  34. +"'doesnotexistorisnotreadable,pleasecheckthepath");
  35. System.exit(1);
  36. }
  37.  
  38.  
  39. try{
  40. //创建索引库IndexWriter
  41. if(writer==null){
  42. initialIndexWriter(indexDir);
  43. }
  44. index(writer,order);
  45. }catch(IOExceptione){
  46. e.printStackTrace();
  47. }
  48. }
  49.  
  50. publicvoidClose()
  51. {
  52. if(null!=writer)
  53. {
  54. writer.close();
  55. }
  56. }
  57.  
  58.  
  59. privatevoidinitialIndexWriter(FileindexDir)throwsIOException{
  60. DirectoryreturnIndexDir=FSDirectory.open(indexDir);
  61. IndexWriterConfigiwc=newIndexWriterConfig(Version.LUCENE_48,newStandardAnalyzer(Version.LUCENE_48));
  62. writer=newIndexWriter(returnIndexDir,iwc);
  63.  
  64. }
  65.  
  66. privatevoidindex(IndexWriterwriter,OrderModelorder)throwsIOException{
  67.  
  68. //创建文档Document
  69. Documentdoc=newDocument();
  70. FieldorderidField=newStringField("orderid",order.orderid,Field.Store.YES);
  71. doc.add(orderidField);
  72.  
  73. ...
  74.  
  75. //向索引库中写入文档内容
  76. writer.addDocument(doc);
  77. }
  78. }
  79. }

七、组合条件查询

由java类实现查询,因为PHP可以直接调用java程序,所以PHP只需要把java类返回的结果显示出来就可以。

  1. intpageIndex=1;
  2. intpageSize=1;
  3. intstart=(pageIndex-1)*pageSize;
  4.  
  5. Stringquery_fields[]=newString[]{"filename","content"};//对哪几个字段进行查询检索
  6. Filefile_index_dir=newFile(indexDir);
  7. try{
  8. Directorydirectory=newSimpleFSDirectory(file_index_dir);
  9. IndexReaderindexReader=DirectoryReader.open(directory);
  10.  
  11. //创建搜索
  12. IndexSearcherindexSearcher=newIndexSearcher(indexReader);
  13.  
  14. TermQueryquery1=newTermQuery(newTerm("orderid",orderid));
  15. TermQueryquery2=newTermQuery(newTerm("contact",contact));
  16. BooleanQueryquery=newBooleanQuery();
  17. query.add(query1,BooleanClause.Occur.MUST);
  18. query.add(query2,BooleanClause.Occur.MUST);
  19.  
  20. intmax_result_size=start+pageSize;
  21.  
  22. TopscoreDocCollectortopDocs=TopscoreDocCollector.create(max_result_size,false);
  23. indexSearcher.search(query,topDocs);
  24.  
  25. introwCount=topDocs.getTotalHits();//满足条件的总记录数
  26. intpages=(rowCount-1)/pageSize+1;//计算总页数
  27. TopDocstds=topDocs.topDocs(start,pageSize);
  28. scoreDoc[]scoreDoc=tds.scoreDocs;
  29.  
  30. for(inti=0;i<scoreDoc.length;i++){
  31. //内部编号
  32. intdoc_id=scoreDoc[i].doc;
  33.  
  34. //根据文档id找到文档
  35. Documentmydoc=indexSearcher.doc(doc_id);
  36.  
  37. //读取搜索结果
  38. mydoc.get("orderid");
  39. mydoc.get("contact");
  40. mydoc.get("addr");
  41. ...
  42. }
  43. }catch(Exceptione){
  44. e.printStackTrace();
  45. }

有问题可以加我QQ沟通:10980327

猜你在找的NoSQL相关文章