您的位置:首页 > 其它

Lucene-搜索的入门例子

2010-05-09 17:13 375 查看
package org.sam.demo.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;

/**
* @author Sam
* @copyright_code 123456789987654321
* @Date 2008-09-16
* */
public class Search {
private final String PATH="E:/Lucene/Index6/";
/* 关于搜索lucene提供了很多类,基本上需要用的也不多,所以这里我就写一些比较常用的! */
public static void main(String[] args) throws CorruptIndexException, IOException, ParseException {
//		new Search().termSearch("lname","Carson");

String[] keys = {"state","city"};
String[] values = {"CA","Oakland"};
new Search().booleanSerach(keys,values);
}

public void termSearch(String key,String value) throws CorruptIndexException, IOException, ParseException{
QueryParser qp = new QueryParser(key,new StandardAnalyzer());
IndexSearcher search = new IndexSearcher(PATH);
Query tq = qp.parse(value);
Hits hits = search.search(tq);
System.out.println(hits.length());
for(int i = 0 ; i < hits.length() ;i++){
System.out.println(hits.doc(i).get(key));
}
search.close();
}

public void booleanSerach(String[] keys,String[] values) throws CorruptIndexException, IOException, ParseException{
QueryParser qp = null;
BooleanQuery bq = null;
IndexSearcher search = new IndexSearcher(PATH);
for(int i = 0 ; i < keys.length ; i++){
qp = new QueryParser(keys[i],new StandardAnalyzer());
Query tq = qp.parse(values[i]);
bq = new BooleanQuery();
bq.add(tq, BooleanClause.Occur.MUST);
}
Hits hits = search.search(bq);
System.out.println(hits.length());
for(int i = 0 ; i < hits.length() ;i++){
for(int j = 0 ; j < keys.length ; j++)
System.out.print(hits.doc(i).get(keys[j])+"  ");
System.out.println();
}
search.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: