使用lucene

时间:2017-03-27 12:18:54

标签: java android json indexing lucene

是否可以使用lucene在本机Android应用程序中脱机索引文档?

我们为网络构建它,但寻找可在本机Android应用程序中脱机工作的东西。

示例数据:

[ { "名称":" ABC&#34 ;, " desc":"脱机文档" }, { "名称":" JJJ&#34 ;, " desc":"索引我的数据" } ]

我必须索引我的数据并从中搜索

分析器代码:

//  Directory dir = FSDirectory.open("/libs/g");
//Analyzer analyzer = new StandardAnalyzer();
// IndexWriterConfig iwc = new IndexWriterConfig();
// Analyzer analyzer = new StandardAnalyzer();

Directory directory = new RAMDirectory();
// To store an index on disk, use this instead:
//Directory directory = FSDirectory.open("/tmp/testindex");
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_4,new Analyzer(){

protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
    return null;
    }
});
config.setOpenMode(OpenMode.CREATE_OR_APPEND);
indexWriter = new IndexWriter(directory, config);

//Always overwrite the directory
//iwriter.setOpenMode(OpenMode.CREATE);
//indexWriter = new IndexWriter(dir, iwc);

1 个答案:

答案 0 :(得分:2)

将此作为基础http://www.avajava.com/tutorials/lessons/how-do-i-use-lucene-to-index-and-search-text-files.html

并使用它将JSON对象添加到索引

public void addDocuments(IndexWriter indexWriter, JSONArray jsonObjects) {
    for (JSONObject object : (List<JSONObject>) jsonObjects) {
        Document doc = new Document();
        final FieldType bodyOptions = new FieldType();
        bodyOptions.setIndexed(true);
        bodyOptions.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
        bodyOptions.setStored(true);
        bodyOptions.setStoreTermVectors(true);
        bodyOptions.setTokenized(true);
        for (String field : (Set<String>) object.keySet()) {
            doc.add(new Field(field, (String) object.get(field), bodyOptions));
        }
        try {
            System.out.println(doc);
            indexWriter.addDocument(doc);
        } catch (IOException ex) {
            System.err.println("Error adding documents to the index. " + ex.getMessage());
        }
    }
}

您可能需要添加以下依赖项

<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-analyzers-common -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-analyzers-common</artifactId>
    <version>4.10.4</version>
</dependency>