草庐IT

elasticsearch - 从 Golang 查询 ElasticSearch

coder 2023-07-03 原文

Sense 中给定一个 Go 查询字符串

GET employee/info/_search
{
    "query":{
        "bool": {
            "should": [
               {"match": {"name": "Rodri"}},
                {"match": {"name": "Massadra"}}
            ]
        }
    }
}

如何从 ElasticSearch 获取响应。此查询适用于 Sense。 这就是我尝试从 ElasticSearch 获得响应的方式:编码字符串并调用 ElasticSearch

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

func main() {
    query := `{
        "query":{
            "bool": {
                "should": [
                {"match": {"name": "Rodri"}},
                {"match": {"name": "Massadra"}}
                ]
            }
        }
        }`
    query = url.QueryEscape(query)
    resp, err := http.Get("http://localhost:9200/employee/info/_search?q=" + query)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    fmt.Printf("\n%s", body)
}

这是我得到的错误:

{"error":{"root_cause":[{"type":"query_parsing_exception","reason":"
Failed to parse query [{\n\t\t\"query\":{\n\t\t\t\"bool\": 
{\n\t\t\t\t\"should\": [\n\t\t\t\t{\"match\": {\"name\": \"Rodri\"}},
\n\t\t\t\t{\"match\": {\"name\": \"Massadra\"}}\n\t\t\t\t]\n\t\t\t}\n\t\t}\n\t\t}]",
"index":"employee"}],"type":"search_phase_execution_exception",
"reason":"all shards failed","phase":"query","grouped":true,
"failed_shards":[{"shard":0,"index":"employee","node":"EbSLFZXfRCGoqnPcGsoNAg",
"reason":{"type":"query_parsing_exception","reason":"Failed to parse query
 [{\n\t\t\"query\":{\n\t\t\t\"bool\": {\n\t\t\t\t\"should\":
 [\n\t\t\t\t{\"match\": {\"name\": \"Rodri\"}},\n\t\t\t\t{\"match\": 
{\"name\": \"Massadra\"}}\n\t\t\t\t]\n\t\t\t}\n\t\t}\n\t\t}]","index":"employee",
"caused_by":{"type":"parse_exception","reason":
"Cannot parse '{\n\t\t\"query\":{\n\t\t\t\"bool\": {\n\t\t\t\t\"should\": [\n\t\t\t\t{\"match\":
 {\"name\": \"Rodri\"}},\n\t\t\t\t{\"match\": {\"name\": \"Massadra\"}}\n\t\t\t\t]\n\t\t\t}\n\t\t}\n\t\t}': 
Encountered \" <RANGE_GOOP> \"[\\n\\t\\t\\t\\t{\\\"match\\\": \"\" 
at line 1, column 41.\nWas expecting one of:\n    \"]\" ...\n    \"}\" ...\n   
 ","caused_by":{"type":"parse_exception","reason":"Encountered \" <RANGE_GOOP> 
\"[\\n\\t\\t\\t\\t{\\\"match\\\": \"\" at line 1, column 41.\nWas expecting one

我也试试这个client但我没有找到从字符串查询中使用它的方法。

谢谢

最佳答案

一般来说,发送有效负载时应该使用 POST 而不是 GET(即使 ES 接受 GET 请求中的有效负载)。

试试这个代码:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    url := "http://localhost:9200/employee/info/_search"
    query := []byte(`{
            "query":{
                "bool": {
                    "should": [
                    {"match": {"name": "Rodri"}},
                    {"match": {"name": "Massadra"}}
                    ]
                }
            }
            }`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(query))
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    fmt.Printf("\n%s", string(body))
}

关于elasticsearch - 从 Golang 查询 ElasticSearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39309862/

有关elasticsearch - 从 Golang 查询 ElasticSearch的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  3. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  4. ruby-on-rails - solr 清理查询 - 2

    我在Rails上使用带有ruby​​的solr。一切正常,我只需要知道是否有任何现有代码来清理用户输入,比如以?开头的查询。或* 最佳答案 我不知道执行此操作的任何代码,但理论上可以通过查看parsingcodeinLucene来完成并搜索thrownewParseException(只有16个匹配!)。在实践中,我认为您最好只捕获代码中的任何solr异常并显示“无效查询”消息或类似信息。编辑:这里有几个“sanitizer”:http://pivotallabs.com/users/zach/blog/articles/937-s

  5. ruby-on-rails - Rails 3 在一个查询中包含多个表 - 2

    我正在为锦标赛开发一个Rails应用程序。我在这个查询中使用了三个模型:classPlayertruehas_and_belongs_to_many:tournamentsclassTournament:destroyclassPlayerMatch"Player",:foreign_key=>"player_one"belongs_to:player_two,:class_name=>"Player",:foreign_key=>"player_two"在tournaments_controller的显示操作中,我调用以下查询:Tournament.where(:id=>params

  6. ruby-on-rails - Sunspot:如何对具有不同值的多个字段进行全文查询? - 2

    我想用sunspot重现以下原始solr查询q=exact_term_text:fooORterm_textv:foo*ORalternate_text:bar*但我无法通过标准的太阳黑子界面理解这是否可能以及如何实现,因为看起来:fulltext方法似乎不接受多个文本/搜索字段参数我不知道将什么参数作为第一个参数传递给fulltext,就好像我通过了"foo"或"bar"结果不匹配如果我传递一个空参数,我得到一个q=*:*范围过滤器(例如with(:term).starting_with('foo*')(顾名思义)作为过滤器查询应用,因此不参与评分。似乎可以手动编写字符串(或者可能使

  7. ruby-on-rails - 在不重新查询数据库的情况下重新排序 Rails 中的事件记录? - 2

    例如,假设我有一个名为Products的模型,并且在ProductsController中,我有以下代码用于product_listView以显示已排序的产品。@products=Product.order(params[:order_by])让我们想象一下,在product_listView中,用户可以使用下拉菜单按价格、评级、重量等进行排序。数据库中的产品不会经常更改。我很难理解的是,每次用户选择新的order_by过滤器时,rails是否必须查询,或者rails是否能够以某种方式缓存事件记录以在服务器端重新排序?有没有一种方法可以编写它,以便在用户排序时rails不会重新查询结果

  8. ruby-on-rails - 带句点(或句号)的 Rails 查询字符串。 - 2

    我目前正在尝试了解RoR。我将两个字符串传递到我的Controller中。一个是随机的十六进制字符串,另一个是电子邮件。该项目用于对数据库进行简单的电子邮件验证。我遇到的问题是当我输入如下内容来测试我的页面时:http://signup.testsite.local/confirm/da2fdbb49cf32c6848b0aba0f80fb78c/bob.villa@gmailcom我在:email的参数散列中得到的全部是'bob'。我在gmail和com之间留下了.,因为那样会导致匹配根本不起作用。我的路由匹配如下:match"confirm/:code/:email"=>"conf

  9. ruby - Rails Elasticsearch 聚合 - 2

    不知何故,我似乎无法获得包含我的聚合的响应...使用curl它按预期工作:HBZUMB01$curl-XPOST"http://localhost:9200/contents/_search"-d'{"size":0,"aggs":{"sport_count":{"value_count":{"field":"dwid"}}}}'我收到回复:{"took":4,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":90,"max_score":0.0,"hits":[]},"a

  10. ruby - 如何将编码的查询值添加到 URL? - 2

    我正在寻找一种方便实用的方法来将编码值添加到Ruby中的URL查询字符串。目前,我有:require'open-uri'u=URI::HTTP.new("http",nil,"mydomain.example",nil,nil,"/tv",nil,"show="+URI::encode("Rosie&Jim"),nil)pu.to_s#=>"http://mydomain.example/tv?show=Rosie%20&%20Jim"这不是我要找的,因为我需要得到“http://mydomain.example/tv?show=Rosie%20%26%20Jim”,这样show=值就

随机推荐