使用 Java API 进行 ElasticSearch 全文搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14297329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:47:21  来源:igfitidea点击:

ElasticSearch full text search using Java API

javaluceneelasticsearch

提问by Wei Hao

I've recently started exploring the world of search, and am trying to use ES as the index for my MongoDB. I've managed to integrate them successfully, but I find the search API rather complex and confusing. The Java API is not too helpful either. I am able to find exact matches, but how do I do full-text searches? Here is my code:

我最近开始探索搜索领域,并尝试使用 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();

I have no problems finding "name":"testname"using .setQuery(termQuery("name", "testname")), but "name":"this is a test name"doesn't work with the above example. What am I doing wrong?

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

采纳答案by Wei Hao

After crawling the Internet for hours, I've managed to figure it out, with some help from the javadocs. The most important is the interface *QueryBuilder*, and its implementing classes. I used FieldQueryBuilderfor my query, which in shown in the setQuerymethod below.

在互联网上爬了几个小时后,在javadocs 的帮助下,我设法弄明白了。最重要的是 interface*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
}

With the resulting Map object, you can simply call the getmethod to retrieve the relevant data.

使用生成的 Map 对象,您可以简单地调用该get方法来检索相关数据。

回答by mjhm

It looks like termQuery in elasticsearchuses Lucence for it's search syntax. According to the Lucene docsthe "*" wildcard is not allowed as the first term of a search.

看起来elasticsearch 中的 termQuery使用 Lucence 作为它的搜索语法。根据Lucene 文档,“*”通配符不允许作为搜索的第一个术语。