Created
September 23, 2018 11:38
-
-
Save adityakrshnn/2af6d5eaa77cad95070735b8fea9eb7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func fieldValueFactorSearch(index, Type, searchTerm, category, animated string) []Result { | |
client, _ := elastic.NewSimpleClient(elastic.SetURL("http://13.232.108.38:8000"), | |
elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)), | |
elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags))) | |
ctx := context.Background() | |
var Results []Sticker | |
fieldFactor := elastic.NewFieldValueFactorFunction().Field("votes").Modifier("log1p") | |
query := elastic.NewBoolQuery() | |
if searchTerm != "" { | |
query = query.Must(elastic.NewTermQuery("tags", searchTerm)) | |
} | |
if animated != "" { | |
query = query.Filter(elastic.NewTermQuery("animated", animated)) | |
} | |
if category != "" { | |
query = query.Filter(elastic.NewTermQuery("category", category)) | |
} | |
functionScore := elastic.NewFunctionScoreQuery().Query(query).AddScoreFunc(fieldFactor) | |
src, _ := functionScore.Source() | |
data, _ := json.Marshal(src) | |
searchResult, err := client.Search(). | |
Index(index). | |
Type(Type). | |
Query(elastic.NewRawStringQuery(string(data))). | |
From(0).Size(100). | |
Do(ctx) | |
if err != nil { | |
panic(err) | |
} | |
if searchResult.Hits.TotalHits > 0 { | |
fmt.Printf("Found a total of %d Stickers in Exact Search\n", searchResult.Hits.TotalHits) | |
// Iterate through results | |
for _, hit := range searchResult.Hits.Hits { | |
// hit.Index contains the name of the index | |
// Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}). | |
var t Sticker | |
err := json.Unmarshal(*hit.Source, &t) | |
if err != nil { | |
fmt.Println("Deserialization failed") | |
} | |
Results = append(Results, t) | |
} | |
} | |
if len(result) == 0 { | |
fmt.Println("No results found") | |
} | |
return Results | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment