実際、クエリを 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
抜粋ですのでご了承ください。さらに、実際の検索を実行してから、suggestedQuery 属性を searchResult マップに追加しています。
Elastic Search で実行されている _suggest サービスに対して HTTP POST を実行します。私の例では、これは単一のサーバーで実行される単純な Web アプリケーションであったため、localhost は問題ありませんでした。リクエストの形式は、Elastic Search のドキュメントに基づいた JSON オブジェクトです。
2 つの応答ハンドラーがあります。1 つは成功用、もう 1 つはエラー用です。私のサクセス ハンドラーは、提案が与えられた各単語を繰り返し処理し、それぞれに最適な (最初の) 提案があればそれを選びます。生データを見たい場合は、一時的に追加できますprintln(json)
。
最後に 1 つ注意してください - プロジェクトに httpBuilder クラスを追加するとき、すでに提供されているいくつかのアーティファクトを除外する必要がある可能性があります。すなわち:
runtime('org.codehaus.groovy.modules.http-builder:http-builder:0.5.1') {
excludes 'xalan'
excludes 'xml-apis'
excludes 'groovy'
}