ElasticSearch使用Java API进行全文搜索

Wei*_*Hao 8 java lucene elasticsearch

我最近开始探索搜索世界,并尝试使用ES作为MongoDB的索引.我成功地将它们集成在一起,但我发现搜索API相当复杂和令人困惑.Java API也没有太大帮助.我能找到完全匹配的内容,但如何进行全文搜索?这是我的代码:

Settings settings = ImmutableSettings.settingsBuilder()
    .put("cluster.name", "elasticsearch").build();
Client client = new TransportClient(settings)
    .addTransportAddress(new InetSocketTransportAddress("host-ip", 9300));
SearchResponse response = client.prepareSearch("mongoindex")
    .setSearchType(SearchType.QUERY_AND_FETCH)
    .setQuery(termQuery("name", "*name*"))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();
Run Code Online (Sandbox Code Playgroud)

我找到"name":"testname"使用没有问题.setQuery(termQuery("name", "testname")),但"name":"this is a test name"不适用于上面的例子.我究竟做错了什么?

Wei*_*Hao 8

在网上爬了几个小时之后,我已经设法在javadocs的帮助下解决了这个问题.最重要的是接口*QueryBuilder*及其实现类.我用于FieldQueryBuilder我的查询,在setQuery下面的方法中显示.

SearchResponse response = client.prepareSearch("mongoindex")
    .setSearchType(SearchType.QUERY_AND_FETCH)
    .setQuery(fieldQuery("name", "test name"))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();
SearchHit[] results = response.getHits().getHits();
for (SearchHit hit : results) {
  System.out.println(hit.getId());    //prints out the id of the document
  Map<String,Object> result = hit.getSource();   //the retrieved document
}
Run Code Online (Sandbox Code Playgroud)

使用生成的Map对象,您只需调用该get方法即可检索相关数据.