lucene4.7实例详解

java.lang.UnsupportedClassVersionError: org/apache/lucene/index/IndexableField : Unsupported major.minor version 51.0
Apache Lucene 4.8.0发布:不再支持Java 6,因为Lucene4.9要求Java版本最低为Java7,本人用的是4.7.2因为我安装的是jdk6

 一。lucene4.7版本的实例1

public class IndexFile {

    protected String[] ids={"1", "2"};

    protected String[] content={"Amsterdam has lost of add  cancals", "i love  add this girl"};

    protected String[] city={"Amsterdam", "Venice"};

    private Directory dir;
    /**
     * 初始添加文档
     * @throws Exception
     */
    @Before
    public void init() throws Exception {
        String pathFile="E:/indexPath";//创建索引存放位置
       //1.4 通过Analyzer 的创建指定索引语言词汇的分析器
        Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_47);
        
       //1.3 通过IndexWriterConfig的创建指定索引版本和语言词汇分析器
       IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_47, analyzer);
        
        //1.2 通过Directory的创建指定索引存放位置
        dir=FSDirectory.open(new File(pathFile));
        
        //1.1 创建IndexWriter,它的作用是用来写索引文件,
	//可以将IndexWriter看做是一个特定类型的数据库,用来存放各种表,可以将Document看做是一张张的表
	//该方法有两个参数,第一个dir参数为索引存放位置,参数类型为Directory,第二个参数conf为 IndexWriter的配置类
        IndexWriter writer = new IndexWriter(dir, iwc);
        
        for(int i=0; i < ids.length; i++) {
        <span style="white-space:pre">	</span>//2.1 创建Document指定要索引的文档
	<span style="white-space:pre">	</span>//可以将Document看做是数据库中的一张张的表,而每个field都是表中的一个colum用来存放各种类型的信息,如标题、作者、时间等等
            Document doc=new Document();
            doc.add(new StringField("id", ids[i], Store.YES));
            doc.add(new TextField("content", content[i], Store.YES));
            doc.add(new StringField("city", city[i], Store.YES));
            writer.addDocument(doc);
        }
      //2.2表(Document)创建好之后,当然要添加到数据库(IndexWriter)中,同时commit
        writer.commit();
        writer.close();
    }

    /**
     * 查询
     * @throws Exception
     */
    @Test
    public void search() throws Exception {
        String filePath="E:/indexPath";
        //1.3 指定搜索目录
        Directory dir=FSDirectory.open(new File(filePath));
      
        //1.2创建IndexReader将搜索目录读取到内存
        IndexReader reader=DirectoryReader.open(dir);
        //1.1创建IndexSearcher准备搜索
        IndexSearcher searcher=new IndexSearcher(reader);
        //2.3 在content索引区搜索关键字“add”
        Term term=new Term("content", "add");
	    //2.2 创建Query生成查询语法树
        TermQuery query=new TermQuery(term);
        //2.1 获取搜索结果,搜索相似度最高的5条记录
        TopDocs topdocs=searcher.search(query, 5);
        ScoreDoc[] scoreDocs=topdocs.scoreDocs;
        System.out.println("查询结果总数: " + topdocs.totalHits+"   最大的评分:"+topdocs.getMaxScore());
        for(int i=0; i < scoreDocs.length; i++) {
            int doc = scoreDocs[i].doc;
            Document document = searcher.doc(doc);//命中的文件
            System.out.println("content===="+document.get("content"));
            System.out.println("id:" + scoreDocs[i].doc + "  score:" + scoreDocs[i].score+"  index:"+scoreDocs[i].shardIndex);
        }
        reader.close();
    }

}

 二、lucene4.6实例2

public class Constants {
	public final static String INDEX_FILE_PATH = "F:\lucene\test"; //索引的文件的存放路径 测试时可以在本目录下自行建一些文档,内容自行编辑即可
    public final static String INDEX_STORE_PATH = "F:\lucene\index"; //索引的存放位置
}

 

public class LuceneIndex {
	
	/**
	 * 创建索引
	 * @param analyzer
	 * @throws Exception
	 */
	public static void createIndex(Analyzer analyzer) throws Exception{
		Directory dire=FSDirectory.open(new File(Constants.INDEX_STORE_PATH));
		IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_46, analyzer);
		IndexWriter iw=new IndexWriter(dire, iwc);
		this.addDoc(iw);
		iw.close();
	}
	
	/**
	 * 动态添加Document
	 * @param iw
	 * @throws Exception
	 */
	public static void addDoc(IndexWriter iw)  throws Exception{
		File[] files=new File(Constants.INDEX_FILE_PATH).listFiles();
		for (File file : files) {
			Document doc=new Document();
			String content=LuceneIndex.getContent(file);
			String name=file.getName();
			String path=file.getAbsolutePath();
			doc.add(new TextField("content", content, Store.YES));
			doc.add(new TextField("name", name, Store.YES));
			doc.add(new TextField("path", path,Store.YES));
			System.out.println(name+"==="+content+"==="+path);
			iw.addDocument(doc);
			iw.commit();
		}
	}
	
	/**
	 * 获取文本内容
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public static String getContent(File file) throws Exception{
		FileInputStream fis=new FileInputStream(file);
		InputStreamReader isr=new InputStreamReader(fis);
		BufferedReader br=new BufferedReader(isr);
		StringBuffer sb=new StringBuffer();
		String line=br.readLine();
		while(line!=null){
			sb.append(line+"
");
			line=null;
		}
		return sb.toString();
	}
	
	/**
	 * 搜索
	 * @param query
	 * @throws Exception
	 */
	private static void search(Query query) throws Exception {
		Directory dire=FSDirectory.open(new File(Constants.INDEX_STORE_PATH));
		IndexReader ir=DirectoryReader.open(dire);
		IndexSearcher is=new IndexSearcher(ir);
		TopDocs td=is.search(query, 1000);
		System.out.println("共为您查找到"+td.totalHits+"条结果");
		ScoreDoc[] sds =td.scoreDocs;
		for (ScoreDoc sd : sds) { 
			Document d = is.doc(sd.doc); 
			System.out.println(d.get("path") + ":["+d.get("path")+"]"); 
		}
	}	
	
	public static void main(String[] args) throws Exception, Exception {
		Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_46);
		LuceneIndex.createIndex(analyzer);
		QueryParser parser = new QueryParser(Version.LUCENE_46, "content", analyzer); 
		Query query = parser.parse("人");
		LuceneIndex.search(query);
	}
}

  

 

 

原文地址:https://www.cnblogs.com/estellez/p/4935060.html