indexsearch.java

来自「java程序编写的lucene环境下的搜索器的源代码」· Java 代码 · 共 70 行

JAVA
70
字号
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package lucenesearch;import java.awt.Component;import org.apache.lucene.index.Term;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.Hits;import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;/** * * @author BileiZhu */public class IndexSearch {    IndexSearch(String indexDirectory, String keyWords, boolean mode, int type) {        try {            IndexSearcher searcher = new IndexSearcher(indexDirectory);            Term term = null;            TermQuery termQuery = null;            Hits hits = null;            if (type == 0) {                term = new Term("contents", keyWords.toLowerCase());                termQuery = new TermQuery(term);                SortField[] sf = null;                if (mode) {                    sf = new SortField[]{SortField.FIELD_SCORE, new SortField(null, SortField.DOC, true)};                } else {                    sf = new SortField[]{new SortField(null, SortField.SCORE, true), new SortField(null, SortField.DOC, true)};                }                Sort sort = new Sort(sf);                hits = searcher.search(termQuery, sort);            } else if (type == 1) {                term = new Term("title", keyWords.toLowerCase());                termQuery = new TermQuery(term);                SortField[] sf = null;                if (mode) {                    sf = new SortField[]{SortField.FIELD_SCORE, new SortField(null, SortField.DOC, true)};                } else {                    sf = new SortField[]{new SortField(null, SortField.SCORE, true), new SortField(null, SortField.DOC, true)};                }                Sort sort = new Sort(sf);                hits = searcher.search(termQuery, sort);            }            System.out.println("共有" + searcher.maxDoc() + "条索引,命中" + hits.length() + "条");            for (int i = 0; i < hits.length(); i++) {                int DocId = hits.id(i);                String DocPath = hits.doc(i).get("path");                System.out.print(Float.toString(hits.score(i)) + "    " + DocPath);            }        } catch (Exception e) {            System.out.println(e);        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?