`
supben
  • 浏览: 326527 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

lucune小例

 
阅读更多
基于3.5

package com.supben;

import java.io.File;

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.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 索引建立类
 * 
 */
public class IndexMaker {

	private static File INDEX_DIR = new File("./index");// 索引文件夹

	public static void make(String id, String name, String desc) {

		try {
			// 字段ID,可查询,不分词
			Field ID = new Field("id", id, Field.Store.YES, Field.Index.NOT_ANALYZED);

			// 字段NAME,可查询,分词
			Field NAME = new Field("name", name, Field.Store.YES, Field.Index.ANALYZED);

			// 字段描述,可查询,分词
			Field DESC = new Field("desc", desc, Field.Store.YES, Field.Index.ANALYZED);
			Document d = new Document();
			d.add(ID);
			d.add(NAME);
			d.add(DESC);

			IndexWriter iw = new IndexWriter(FSDirectory.open(INDEX_DIR), new IndexWriterConfig(Version.LUCENE_35,
					new StandardAnalyzer(Version.LUCENE_35)));
			iw.addDocument(d);
			iw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		make("1", "shen yuhan", "god is a girl");
		make("2", "shen chenglong", "this is man");
		make("3", "li supben", "war3 tower rpg man");
		make("4", "hu jintao", "is a dog");
	}
}



package com.supben;

import java.io.File;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;

public class Searcher {

	private static File INDEX_DIR = new File("./index");// 索引文件夹

	public static void getAll() {
		try {
			IndexSearcher searcher = new IndexSearcher(FSDirectory.open(INDEX_DIR));
			TermQuery query = new TermQuery(new Term("name", "shen"));
			TopDocs topdocs = searcher.search(query, 10);
			ScoreDoc[] hits = topdocs.scoreDocs;
			for (ScoreDoc hit : hits) {
				Document doc = searcher.doc(hit.doc);
				String id = doc.get("id");
				String name = doc.get("name");

				System.out.println("查询的文档的id是:" + id + ",名称是:" + name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		getAll();
	}
}


  • 大小: 8.2 KB
1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics