/** * 多索引进行查询 */ public void testCreateIndex() { Analyzer analyzer = new IKAnalyzer(); String atext ="明年起,杭州将对两区五县(市)居民发放市民卡,实现杭州市域范围医保“一卡通”凭卡就医。12月底,首批发卡工作将拉开帷幕"; String btext ="搜索操作为每个Searchable分配一个线程市民卡,直到所有线程都完成其搜索。基本搜索和进行过滤的搜索是并行执行的"; Directory a = new RAMDirectory(); Directory b = new RAMDirectory(); IndexWriter awriter; IndexWriter bwriter; IndexSearcher[] searchers; try { awriter = new IndexWriter(a, analyzer, true ,IndexWriter.MaxFieldLength.LIMITED); Document adoc = new Document(); adoc.add(new Field("aid", "1", Field.Store.YES,Field.Index.ANALYZED)); adoc.add(new Field("doc", atext, Field.Store.YES,Field.Index.ANALYZED)); adoc.add(new Field("name", "张三", Field.Store.YES,Field.Index.NOT_ANALYZED)); awriter.addDocument(adoc); awriter.close(); bwriter = new IndexWriter(b, analyzer, true ,IndexWriter.MaxFieldLength.LIMITED); Document bdoc = new Document(); bdoc.add(new Field("bid", "1", Field.Store.YES,Field.Index.ANALYZED)); bdoc.add(new Field("doc", btext, Field.Store.YES,Field.Index.ANALYZED)); bdoc.add(new Field("name", "李四", Field.Store.YES,Field.Index.NOT_ANALYZED)); bwriter.addDocument(bdoc); bwriter.close(); searchers = new IndexSearcher[2]; searchers[0]=new IndexSearcher(a); searchers[1]=new IndexSearcher(b); MultiSearcher searcher=new MultiSearcher(searchers); //对2个索引进行搜索 String[] fields =new String[]{"aid","doc","name"}; Query query=IKQueryParser.parseMultiField(fields, "张三"); // Query query=IKQueryParser.parse("doc", "市民卡"); TopDocs topDocs = searcher.search(query, 200); ScoreDoc[] hits = topDocs.scoreDocs; for (int i = 0; i < hits.length; i++) { Document doc = searcher.doc(hits[i].doc); System.out.println("name:"+doc.get("name")); System.out.println("aid:"+doc.get("aid")+"bid:"+doc.get("bid")); System.out.println("doc:"+doc.get("doc")); } assertNotNull(topDocs); } catch (CorruptIndexException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (LockObtainFailedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // List<User> userList = userService.getUserList(); // userIndexService.createIndex(userList); }