Grails ElasticSearch插件-建议查询 [英] Grails ElasticSearch Plugin - Suggest Query

本文介绍了Grails ElasticSearch插件-建议查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!


是否可以使用插件编写建议查询? 插件文档中没有关于此的任何内容. 如果可能的话,该怎么办?

Is it possible to write a suggest query using the plugin? There's nothing about that in the plugin documentation. If it's possoble, how do I do that?


Here's the elasticsearch docs about suggest querys:



实际上,您确实需要将查询直接发送到Elastic Search.下面是我使用的代码:

Indeed, you do need to send the query directly to Elastic Search. Below is the code I used:

import org.apache.commons.lang.StringUtils
import org.apache.commons.lang.math.NumberUtils

def suggestion = params.query

def http = new HTTPBuilder('http://localhost:9200/_suggest')
http.request(Method.POST, ContentType.JSON) {
    body = [
            'suggestion': [
                    'text': params.query,
                    'term': ["field": "_all"]

    response.success = { resp, json ->
        json?.suggestion?.each { s ->
            def oldWord = s?.text
            def newWord = s?.options[0]?.text ?: oldWord
            suggestion = StringUtils.replace(suggestion, oldWord, newWord)


    response.failure = { resp ->
        flash.error = "Request failed with status ${resp.status}"
searchResult.suggestedQuery = suggestion


Note, that this is an excerpt. Additionally, I am performing the actual search, then appending the suggestedQuery attribute to the searchResult map.

对通过Elastic Search运行的_suggest服务执行HTTP POST.在我的示例中,这是一个在单个服务器上运行的简单Web应用程序,因此localhost很好.请求的格式是基于Elastic Search

Perform an HTTP POST to the _suggest service running with Elastic Search. In my example, this was a simple web application running on a single server, so localhost was fine. The format of the request is a JSON object based off of the Elastic Search documentation.


We have two response handlers - one for success, another for errors. My success handler iterates over each word that a suggestion was given for and picks the best (first) suggestion for each one, if there is one. If you want to see the raw data, you can temporarily add in println(json).


One last note - when adding the httpBuilder classes to the project you are likely to need to exclude a few artifacts that are already provided. Namely:

runtime('org.codehaus.groovy.modules.http-builder:http-builder:0.5.1') {
    excludes 'xalan'
    excludes 'xml-apis'
    excludes 'groovy'

这篇关于Grails ElasticSearch插件-建议查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
发送“验证码”获取 | 15天全站免登陆