使用弹性搜索进行文档搜索

时间:2017-01-20 12:40:28

标签: java elasticsearch

我不熟悉弹性搜索,需要帮助来了解如何使用弹性搜索从文档列表中搜索文本。例如,用户通过我的应用程序上传文档列表,并基于某些关键字,如姓名,年龄i必须得到文件。

我已经尝试了很多东西来获取一个示例java程序来理解弹性搜索在上面的场景中是如何工作的。有些人可以帮助我获得示例程序。

我已经使用apache lucene进行了文件搜索,但它无法正常工作。可以帮助我找到代码中的错误

公共类App {

public static void main(String[] args) throws IOException {

    String path = "D:\\input\\output\\test.txt";      
    List<File> files = getFiles(path);

    createIndex(files);
    List<String> searchkeywords = new ArrayList<String>();
    searchkeywords.add("sample");
    int count = searchIndex(searchkeywords);
    System.out.println("count :: "+count);

}   

public static void createIndex(List<File> files) throws IOException {
    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory directory = FSDirectory.open(Paths.get("index"));
    IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
    IndexWriter indexWriter = new IndexWriter(directory, iwc);
    for (File file : files) {
        Document document = new Document();
        Field pathField = new StringField("contents", file.toString(), Field.Store.YES);
        document.add(pathField);
        if (indexWriter.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
            System.out.println("adding " + file);
            indexWriter.addDocument(document);
        } else {
            System.out.println("updating " + file);
            indexWriter.updateDocument(new Term("path", file.toString()), document);
            indexWriter.addDocument(document);
        }
        indexWriter.close();
    }
}


public static int searchIndex(List<String> searchStrings) throws IOException, ParseException {
    int maxCount = 0;
    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get("index")));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();
    QueryParser parser = new QueryParser("contents", analyzer);
    for (String searchString : searchStrings) {
        Query query = parser.parse(searchString);
        TopDocs result = searcher.search(query, 10);
        maxCount += result.totalHits;
    }
    return maxCount;
} 

}

0 个答案:

没有答案