Lucene4.4 IntField怎么才能搜索到?

喜欢西瓜 发布于 2013/08/22 09:12
阅读 1K+
收藏 1
package test;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatField;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;

public class Lucene44TC {

	@Test
	public void test() throws IOException, ParseException {

		File file = new File("c://index_");
		if (file.exists()) {
			File[] f = file.listFiles();

			for (int i = 0; i < f.length; i++) {
				f[i].delete();
			}
		} else {
			file.mkdirs();

		}
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);
		Directory

		indexDir = new SimpleFSDirectory(file);

		IndexWriter writer = new IndexWriter(indexDir, new IndexWriterConfig(
				Version.LUCENE_44, analyzer));

		for (int i = 0; i < 100; i++) {

			Document doc = new Document();
			doc.add(new IntField("ids", 10000000 + i, Field.Store.YES));
			doc.add(new StringField("id", "10000000" + i, Field.Store.YES));
			doc.add(new StringField("test1", "美好的明天" , Field.Store.YES));
			doc.add(new TextField("title", "GOAT BLOOD in Sodium Citrate" + i,
					Field.Store.NO));

			doc.add(new FloatField("score", 59.9F, Field.Store.YES));

			writer.addDocument(doc);

		}

		writer.forceMerge(1, true);
		writer.close();

		// ////////////////////////////

		IndexSearcher searcher = null;
		searcher = new IndexSearcher(DirectoryReader.open(indexDir));
		// (1第一种不行)
		Query q = new QueryParser(Version.LUCENE_44, "ids", analyzer)
				.parse("10000001");  //no
		// (2第二种也不行)
		//  q = new TermQuery(new Term("ids", "10000001"));  no
		//  q = new TermQuery(new Term("test1", "美好的明天")); ok

		System.out.println(q);
		TopDocs hits = searcher.search(q, 10);
		System.out.println(hits.totalHits);
		for (int i = 0; i < hits.scoreDocs.length; i++) {
			int docId = hits.scoreDocs[i].doc;
			Document hit = searcher.doc(docId);
			System.out.println(hit.toString());
		}

	}
}
以上是代码,我怎么才能搜索到Intfield这个字段
加载中
0
_波波
_波波

搜索的时候可以用NumericRangeQuery.

例如:

q = NumericRangeQuery.newIntRange("ids", 10000001, 10000001, true, true);

这样就能搜索到结果了。

0
ran
ran

好别扭

返回顶部
顶部