实际上,您确实需要将查询直接发送到 Elastic Search。下面是我使用的代码:
import groovyx.net.http.ContentType
import groovyx.net.http.Method
import org.apache.commons.lang.StringUtils
import org.apache.commons.lang.math.NumberUtils
import groovyx.net.http.HTTPBuilder
...
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
请注意,这是摘录。此外,我正在执行实际搜索,然后将建议查询属性附加到 searchResult 映射。
对使用 Elastic Search 运行的 _suggest 服务执行 HTTP POST。在我的示例中,这是一个在单个服务器上运行的简单 Web 应用程序,因此 localhost 很好。请求的格式是基于 Elastic Search文档的 JSON 对象。
我们有两个响应处理程序——一个用于成功,另一个用于错误。我的成功处理程序会遍历给出建议的每个单词,并为每个单词选择最好的(第一个)建议(如果有的话)。如果要查看原始数据,可以临时添加println(json)
.
最后一点 - 在将 httpBuilder 类添加到项目时,您可能需要排除一些已经提供的工件。即:
runtime('org.codehaus.groovy.modules.http-builder:http-builder:0.5.1') {
excludes 'xalan'
excludes 'xml-apis'
excludes 'groovy'
}