簡體   English   中英

如何使用Lucene查詢ElasticSearch索引

[英]How to use Lucene to query ElasticSearch index

我可以使用Lucene查詢ElasticSearch索引嗎?

使用ElasticSearch我創建了一個索引並插入了這三個文檔:

$ curl -XPOST localhost:9200/index1/type1 -d '{"f1":"dog"}'
$ curl -XPOST localhost:9200/index1/type2 -d '{"f2":"cat"}'
$ curl -XPOST localhost:9200/index1/type2 -d '{"f3":"horse"}'

所以,我有一個索引,兩個類型和三個文檔。 現在,我想使用標准的Lucene來搜索這些內容。 使用十六進制編輯器,我確定哪個分片具有索引文檔,並且我可以成功查詢該索引。 我無法弄清楚,如何從匹配的文檔中檢索字段值。

以下程序成功搜索但無法檢索結果。

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;

public class TestES {

void doWork(String[] args) throws Exception {
    // Index reader for already created ElasticSearch index
    String indx1 = "/path-to-index/elasticsearch-0.90.0.RC2-SNAPSHOT/data/elasticsearch/nodes/0/indices/index1/1/index";
    Directory index = FSDirectory.open(new File(indx1));
    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);

    // Looks like the query is correct since we do get a hit
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
    Query q = new QueryParser(Version.LUCENE_41, "f2", analyzer).parse("cat");
    TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
    searcher.search(q, collector);
    ScoreDoc[] hits = collector.topDocs().scoreDocs;

    // We do get a hit, but results always displayed as null except for "_uid"
    if (hits.length > 0) {
        int docId = hits[0].doc;
        Document d = searcher.doc(docId);
        System.out.println("DocID " + docId + ", _uid: " + d.get("_uid") );
        System.out.println("DocID " + docId + ", f2: " + d.get("f2") );
    }
    reader.close();
}

public static void main(String[] args) throws Exception {
  TestES hl = new TestES();
  hl.doWork(args);
}
}

Results:
DocID 0, _uid: type2#3K5QXeZhQnit9UXM9_4bng
DocID 0, f2: null

上面的_uid值是正確的。

Eclipse向我展示變量Document d確實有兩個字段:

  • 存儲,索引,標記化,omitNorms <_uid:類型2#3K5QXeZhQnit9UXM9_4bng>
  • 儲存<_source:[7b 22 66 32 22 3a 22 63 61 74 22 7d]>

不幸的是,d.get(“_ source”)也返回null。

如何檢索匹配查詢的文檔字段?

謝謝。

如評論中所述,我需要將字段“_source”檢索為二進制值。 所以這工作:d.getBinaryValue(“_ source”)並檢索[7b 22 66 32 22 3a 22 63 61 74 22 7d],這是{“f2”:“cat”}。 Javanna,謝謝你的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM