lucene 入门

public class Test1 { Analyzer a = new StandardAnalyzer(); final String filepath = "f://test.txt"; final String indexpath = "D://Workspaces//MyEclipse 8.x//Lucene//luceneIndex"; @Test public void cteateIndex() throws CorruptIndexException, LockObtainFailedException, IOException{ File file = new File (filepath); Document doc = new Document();//索引文档建立 doc.add(new Field("name",file.getName(),Store.YES,Index.ANALYZED));//Field中是以键值对形式存储的,Index.ANALYZED索引且分词 doc.add(new Field("content",getContent(file),Store.YES,Index.ANALYZED)); doc.add(new Field("size",String.valueOf(file.length()),Store.YES,Index.NOT_ANALYZED));//索引不分词 doc.add(new Field("path",file.getAbsolutePath(),Store.YES,Index.NO));//不索引不分词 IndexWriter indexwriter = new IndexWriter(indexpath,a,true,MaxFieldLength.LIMITED);//写入生成索引文件 indexwriter.addDocument(doc); indexwriter.close(); } public String getContent(File file) throws IOException{ BufferedReader bos = new BufferedReader(new FileReader(file)); StringBuffer content = new StringBuffer(); String line = ""; while((line = bos.readLine())!=null){ content.append(line); } return content.toString(); } @Test public void searchIndex() throws CorruptIndexException, IOException, ParseException{ String str = "document"; String []fields = {"name","content","size","path"}; QueryParser queryparser = new MultiFieldQueryParser(fields, a);//多条件查询 Query query = queryparser.parse(str);//将String按照规则转换为query Filter filter = null; IndexSearcher indexsearcher = new IndexSearcher(indexpath); TopDocs doc = indexsearcher.search(query, filter, 10000); ScoreDoc[] sds = doc.scoreDocs;//查询到的结果数组 int i = doc.totalHits;//查询到的总记录数量 System.out.println("总共有【"+i+"】条记录"); for(ScoreDoc sd:sds){ int docSn = sd.doc;//获得文档内部编号 Document document = indexsearcher.doc(docSn);//根据文档编号取得对应文档 String name = document.get("name");//获取文档的名字(上面键值对) System.out.println(name); } } } 

你可能感兴趣的:(lucene 入门)