Skip to content

Instantly share code, notes, and snippets.

@olivere
Created March 27, 2017 21:48
Show Gist options
  • Select an option

  • Save olivere/978d517b505f019d2f8c361eb6931688 to your computer and use it in GitHub Desktop.

Select an option

Save olivere/978d517b505f019d2f8c361eb6931688 to your computer and use it in GitHub Desktop.
Elastic issue #493
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package main
import (
"fmt"
"log"
"os"
"golang.org/x/net/context"
elastic "gopkg.in/olivere/elastic.v5"
)
// Tweet is a structure used for serializing/deserializing data in Elasticsearch.
type Tweet struct {
User string `json:"user"`
City string `json:"city,omitempty"`
Suggest *elastic.SuggestField `json:"suggest_field,omitempty"`
}
const (
mapping = `{
"settings":{
"number_of_shards":1,
"number_of_replicas":0
},
"mappings":{
"_default_": {
"_all": {
"enabled": true
}
},
"place":{
"properties":{
"user":{
"type":"keyword"
},
"city":{
"type":"text"
},
"suggest_field":{
"type":"completion"
}
}
}
}
}`
IndexName = "places"
TypeName = "place"
)
func main() {
// Starting with elastic.v5, you must pass a context to execute each service
ctx := context.Background()
// Obtain a client and connect to the default Elasticsearch installation
// on 127.0.0.1:9200. Of course you can configure your client to connect
// to other hosts and configure it in various other ways.
client, err := elastic.NewClient(
elastic.SetTraceLog(log.New(os.Stdout, "", 0)),
)
if err != nil {
// Handle error
panic(err)
}
// Use the IndexExists service to check if a specified index exists.
exists, err := client.IndexExists(IndexName).Do(ctx)
if err != nil {
// Handle error
panic(err)
}
if exists {
_, err = client.DeleteIndex(IndexName).Do(ctx)
if err != nil {
// Handle error
panic(err)
}
}
// Create a new index.
createIndex, err := client.CreateIndex(IndexName).Body(mapping).Do(ctx)
if err != nil {
// Handle error
panic(err)
}
if !createIndex.Acknowledged {
// Not acknowledged
}
// Index a tweet (using JSON serialization)
tweets := []Tweet{
Tweet{
User: "olivere",
City: "Gatlinburg",
// Suggest: elastic.NewSuggestField("gatlinburg"),
},
Tweet{
User: "olivere",
City: "Galenberg",
// Suggest: elastic.NewSuggestField("galenberg"),
},
}
for i, tweet := range tweets {
_, err = client.Index().
Index(IndexName).
Type(TypeName).
Id(fmt.Sprintf("%d", i)).
BodyJson(tweet).
Do(ctx)
if err != nil {
// Handle error
panic(err)
}
}
// Flush to make sure the documents got written.
_, err = client.Flush().Index(IndexName).Do(ctx)
if err != nil {
panic(err)
}
// Suggest
phraseSuggester := elastic.NewPhraseSuggester("place_spelling_suggestions").
Field("city").
Text("Gatlinberg")
searchSource := elastic.NewSearchSource().
Suggester(phraseSuggester).
FetchSource(false).
TrackScores(true).
Timeout("100ms")
searchResult, err := client.Search().
Index(IndexName).
Type(TypeName).
SearchSource(searchSource).
Pretty(true).
Do(ctx)
if err != nil {
// Handle error
panic(err)
}
// searchResult is of type SearchResult and returns hits, suggestions,
// and all kinds of other information from Elasticsearch.
fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
// Delete an index.
deleteIndex, err := client.DeleteIndex(IndexName).Do(ctx)
if err != nil {
// Handle error
panic(err)
}
if !deleteIndex.Acknowledged {
// Not acknowledged
}
}
@olivere
Copy link
Author

olivere commented Mar 27, 2017

Request and response:

POST /places/place/_search?pretty=true HTTP/1.1
Host: 127.0.0.1:9200
User-Agent: elastic/5.0.32 (darwin-amd64)
Transfer-Encoding: chunked
Accept: application/json
Content-Type: application/json
Accept-Encoding: gzip

90
{"_source":false,"suggest":{"place_spelling_suggestions":{"text":"Gatlinberg","phrase":{"field":"city"}}},"timeout":"100ms","track_scores":true}
0


HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

235
{
  "took" : 16,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "suggest" : {
    "place_spelling_suggestions" : [
      {
        "text" : "Gatlinberg",
        "offset" : 0,
        "length" : 10,
        "options" : [
          {
            "text" : "gatlinburg",
            "score" : 0.70695555
          },
          {
            "text" : "galenberg",
            "score" : 0.66353446
          }
        ]
      }
    ]
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment