Grails ElasticSearch Plugin - Suggest Query

♀尐吖头ヾ 提交于 2019-12-13 05:03:37

问题


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:


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'
}


来源:https://stackoverflow.com/questions/25836579/grails-elasticsearch-plugin-suggest-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!