How can I put asterisk in Elasticsearch using Golang library?


(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #1

I already using the library olivere/elastic for elastic search,
this is the Elastic query it’s fine :

PUT i/i/1
{
  "name":"SquadBattle",
  "id": 1
}



PUT i/i/2
{
  "name":"BombSquad",
  "id": 2
}




GET i/_search
{"query": {
    "query_string" : {"default_field" : "name", "query" : "*squad*"}
} }

The problem that I have in Golang, how can put an asterisk
I try this but it does not work :

    package main

import (
	"reflect"
	"fmt"
	"context"
	"github.com/olivere/elastic"
)



func main() {
	fmt.Println("line (42):::", A())
}


func A () []map[string]int {

	ctx := context.Background()
	client, _ := elastic.NewClient()
	client.Ping("http://127.0.0.1:9200").Do(ctx)
	v,_:=client.ElasticsearchVersion("http://127.0.0.1:9200")
	fmt.Println("line(15):::", v)
	m, _ := client.IndexExists("i").Do(ctx)
	fmt.Println("line (17):::", m)
	
	d := ` {"query_string" : {"default_field" : "name", "query" : "*squad*" }}`
	//d := ` {"query_string" : {"default_field" : "name", "query" : "BombSquad" }}`
	
	
	//d:= `{ "match_phrase_prefix":{"name","query": "BombSquad" }}`
	//d :=  `{"match_all":{}}`
	//d := ` {"name", "query" : "squad"}`
	
	myQuery := elastic.NewSimpleQueryStringQuery(d)
	
	searchResult, err := client.Search().Index("i").Query(myQuery).
		From(0).Size(100).Pretty(false).Do(ctx)
	fmt.Println("line (26):::", err)
	type GameStruct struct {
		Name          string  `json:"name"`
		Id            int     `json:"id"`
	}
	
	var (
		mapGameId       =      make(map[string]int)
		sliceMapGameId       []map[string]int
		foundResult          []interface{}
		ttyp                   GameStruct
	)
	
	for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
		foundResult = append(foundResult, item)
		if t, ok := item.(GameStruct); ok {
			//fmt.Printf("elastic by %s: %s\n", t.Name, t.Id)
			mapGameId[t.Name]=t.Id
		}
	}
	sliceMapGameId = append(sliceMapGameId, mapGameId)
	//fmt.Println("line (220):::", sliceMapGameId)
	return sliceMapGameId
}

(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #2

finally, I solved this problem :

myQuery := elastic.NewSimpleQueryStringQuery(d)

instead shoud write :

myQuery := elastic.NewRawStringQuery(d)

That’s very powerful query hope this post help, someone