Grails ElasticSearch Plugin - Suggest Query

2019-09-18 19:45发布

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: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters-completion.html

Thanks very mutch for the answer.

1条回答
爷的心禁止访问
2楼-- · 2019-09-18 20:28

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

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

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

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'
}
查看更多
登录 后发表回答