您的位置:首页 > 其它

lucene内容创建查询Demo

2010-09-27 17:08 218 查看
[color=red]lucene内容创建,查询[/color]

package com.wj.lucene;

import java.io.File;
import java.util.*;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

/**
* Lucene3.0 CRUD操作
*
* @author jcom
* @date 2010-9-28
*
*/
public class CreateAndSearcherIndex {

public static void main(String[] args) throws Exception
{
// 保存索引文件的地方
String indexDir = "D:\\MOST\\data\\test\\indexDir";

// 创建Directory对象
Directory dir = new SimpleFSDirectory(new File(indexDir));

/**
* 创建IndexWriter对象,
* 第一个参数是Directory,
* 第二个是分词器,
* 第三个表示是否是创建, 如果为false为在此基础上面修改,
* 第四表示表示分词的最大值,比如说new MaxFieldLength(2),就表示两个字一分,一般用IndexWriter.MaxFieldLength.LIMITED
*/
IndexWriter indexWriter = new IndexWriter(dir, new StandardAnalyzer(
Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);

//准备加入索引的內容
Map<String, String> maps = new HashMap<String, String>();
maps.put("col1", "east");
maps.put("col2", "south");
maps.put("col3", "west");
maps.put("col4", "north");
maps.put("col5", "center");

/*
* 遍历键,通过键取值
* 循环创建加入
*/
Set set = maps.keySet();
for (Object key : set) {

String keyvalue = key.toString();
String value = maps.get(key);
System.out.println("键:" + keyvalue + " 值:" + value);

Document doc = new Document();
doc.add(new Field(keyvalue, value, Field.Store.YES,
Field.Index.NOT_ANALYZED));
indexWriter.addDocument(doc);
}

//提交关闭
indexWriter.commit();
indexWriter.close();


/**
* 搜索指定内容的字符串
*/
IndexSearcher indexSearch = new IndexSearcher(dir);
QueryParser queryParser = new QueryParser(Version.LUCENE_30, "col5",
new StandardAnalyzer(Version.LUCENE_30));
//指定查询内容
Query query = queryParser.parse("center");
TopDocs hits = indexSearch.search(query, 20);

System.out.println("一共找到:" + hits.totalHits + "条");

for (int i = 0; i < hits.scoreDocs.length; i++)
{
ScoreDoc sdoc = hits.scoreDocs[i];
Document doc = indexSearch.doc(sdoc.doc);
System.out.println("搜索的内容为:"+doc.get("col5"));
}

indexSearch.close();

}
}
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: