I'm working on a beat that interrogate our elastic search, the goal is to get elements in elastics to modify them to avoid duplication.
I've written a search and it works:
client,err :=elasticsearch.NewClient(elasticsearch.ClientSettings{URL:host,Index:indexSel,Username: username,Password: password,Timeout: 60 * time.Second,}, nil)
if err != nil {
log.Fatal(err)
}
params := map[string]string{
"q": "_id:"+maref,
}
_, resp, err := client.SearchURI(index, "", params)
if err != nil {
log.Fatal(err)
return
} else {
fmt.Println(string(resp))
}
And here is the function from the elastic api.go:
func (es *Connection) SearchURI(index string, docType string, params map[string]string) (int, *SearchResults, error) {
status, resp, err := es.apiCall("GET", index, docType, "_search", "", params, nil)
if err != nil {
return status, nil, err
}
result, err := readSearchResult(resp)
return status, result, err
}
func readSearchResult(obj []byte) (*SearchResults, error) {
var result SearchResults
if obj == nil {
return nil, nil
}
err := json.Unmarshal(obj, &result)
if err != nil {
return nil, err
}
return &result, err
}
With the following types:
type SearchResults struct {
Took int `json:"took"`
Shards json.RawMessage `json:"_shards"`
Hits Hits `json:"hits"`
Aggs map[string]json.RawMessage `json:"aggregations"`
}
type Hits struct {
Total int
Hits []json.RawMessage `json:"hits"`
}
For now the answer is a raw JSON:
&{11 [123 34 116 111 116 97 108 34 58 53 44 34 115 117 99 99 101 115 115 102 117 108 34 58 53 44 34 102 97 105 108 101 100 34 58 48 125] {1 [[123 34 95 105 110 100 101 120 34 58 34 99 111 112 105 108 98 101 97 116 45 50 48 49 54 46 49 48 46 50 53 34 44 34 95 116 121 112 101 34 58 34 73 110 99 105 100 101 110 116 34 44 34 95 105 100 34 58 34 65 86 102 54 55 69 103 109 74 66 45 119 85 116 103 82 99 90 113 97 34 44 34 95 115 99 111 114 101 34 58 49 46 48 44 34 95 115 111 117 114 99 101 34 58 123 34 64 116 105 109 101 115 116 97 109 112 34 58 34 50 48 49 54 45 49 48 45 50 53 84 48 56 58 49 54 58 53 55 46 53 53 57 90 34 44 34 97 103 101 110 116 95 105 100 34 58 49 53 44 34 98 101 97 116 34 58 123 34 104 111 115 116 110 97 109 101 34 58 34 53 55 99 53 99 49 57 49 101 48 100 57 34 44 34 110 97 109 101 34 58 34 53 55 99 53 99 49 57 49 101 48 100 57 34 125 44 34 100 101 115 99 114 105 112 116 105 111 110 34 58 34 101 108 97 115 116 105 99 34 44 34 102 105 110 97 108 99 108 97 115 115 34 58 34 34 44 34 105 100 34 58 34 73 45 48 48 53 56 50 54 34 44 34 111 114 103 95 105 100 34 58 49 55 44 34 111 114 103 95 110 97 109 101 34 58 34 83 104 97 109 34 44 34 112 114 105 111 114 105 116 121 34 58 52 44 34 114 101 102 101 114 101 110 99 101 34 58 34 73 45 48 48 53 56 50 54 34 44 34 115 116 97 114 116 95 100 97 116 101 34 58 34 50 48 49 54 45 49 48 45 50 53 84 49 48 58 49 54 58 53 54 46 56 56 49 55 55 52 49 43 48 50 58 48 48 34 44 34 115 116 97 116 117 115 34 58 34 97 115 115 105 103 110 101 100 34 44 34 116 116 111 34 58 48 44 34 116 116 111 95 49 48 48 95 116 114 105 103 103 101 114 101 100 34 58 48 44 34 116 116 114 34 58 48 44 34 116 116 114 95 49 48 48 95 116 114 105 103 103 101 114 101 100 34 58 48 44 34 116 121 112 101 34 58 34 73 110 99 105 100 101 110 116 34 125 125]]} map[]}
So my question is:
How can I convert the result to ascii?
I've read it's probably due to the json.RawMessage type that doesn't convert JSON but I can't find how to convert it.
Thanks by advance,
Plosxh.
EDIT : Solution:
Thx to icza, here's my solution I change my "fmt.Println(resp)" into:
for _, v := range resp.Hits.Hits {
fmt.Println(string(v))
}
It works like a charm!
Edit 2 :
I had to re-create a whole type en json.Unmarshal "resp.Hits.Hits" in order to use it like a regular json.
json.RawMessage is a byte slice:
type RawMessage []byte
You can convert a byte slice to a string with a simple type conversion:
var result SearchResults
// ...
for _, v := range result.Hits {
fmt.Println("Total:", v.Total, "Hits:", string(v.Hits))
}
Or:
fmt.Printf("Total: %d, Hits: %s\n", v.Total, v.Hits)
See this example:
var raw json.RawMessage
raw = json.RawMessage(`something raw`)
fmt.Println(raw)
fmt.Println(string(raw))
fmt.Printf("%s\n", raw)
Output (try it on the Go Playground):
[115 111 109 101 116 104 105 110 103 32 114 97 119]
something raw
something raw
Related
I'm trying to run the below script to get a list of Orgs and the amount of users each Org has:
#!/bin/bash
array=(293 182 177 12 85 51 325 225 40 169 357 329 243 349 291 295 22 279 16 69 219 299 301 331 91 281 285 59 283 341 45 289 95 61 77 13 14 201 43 343 223 28 171 26 233 47 303 367 369 339 257 305 353 245 213 87 345 2 71 199 24 179 259 37 35 237)
for i in "${array[#]}"; do
query=$(export MYSQL_PWD=MYPASS; mysql -e "SELECT COUNT(*) FROM Org.Users WHERE HomeOrgID=$i;")
echo "Org_$i:$query"
done
I expect the result to be a simple "Org:Number" list:
Org_1:150
Org_25:250
Org_17:64
Org_64:12
But the output is not displayed correctly. It does show part of the MySQL statement:
Org_293:COUNT(*)
1
Org_182:COUNT(*)
0
Org_177:COUNT(*)
8
Org_12:COUNT(*)
0
Org_85:COUNT(*)
1
How can I get the output to NOT display that "COUNT(*)" and display just a simple list?
Thanks in advance!
One quick hack : use bash arrays to store your output.
#!/bin/bash
array=(293 182 177 12 85 51 325 225 40 169 357 329 243 349 291 295 22 279 16 69 219 299 301 331 91 281 285 59 283 341 45 289 95 61 77 13 14 201 43 343 223 28 171 26 233 47 303 367 369 339 257 305 353 245 213 87 345 2 71 199 24 179 259 37 35 237)
for i in "${array[#]}"; do
# we store the result of the request as an array
query=($(export MYSQL_PWD=MYPASS; mysql -e "SELECT COUNT(*) FROM Org.Users WHERE HomeOrgID=$i;"))
# we echo the 2nd member of the array. ${query[0]} should contain 'count(*)'
echo "Org_$i:${query[1]}"
done
In a coding contest I have a programming task to find minimum or maximum from different arrays, and the final result to put it at the end of the URL (www.example.com/result).
I can't figure out what format are they expecting...
They gave this hint:
look at the resulting values and see if they could represent something familiar), at the end of the root of the URL of the page you're on (of course add a slash if needed)
Update
For the result of the problem, you need to figure out a way to convert those numbers to a "URL friendly form" value.
For example, a URL friendly value means a string, so you need a 'standard' way to convert each number to a character and use the resulting string to go to the next problem.
I tried the following formats 1:2:3:4 , 1_2_3_4 no chance.
The numbers are 100,126,114,85,82,121,54 .
So I need them formatted in an url friendly form whatever that would mean.
This is the coding challenge :
You are given an input file containing:
On the first line a positive integer N
On the following N lines there will be arrays of integers, of variable length, each integer value separated by a white space from the next value
The start of each array will only contain one of the following possible numbers: 1 or -1
To get to the next step you will have to calculate the minimum (if start value is -1) or maximum (if start value is 1) of the arrays in the input file and then put the result, in a more human and URL friendly form (hint: look at the resulting values and see if they could represent somehting familiar), at the end of the root of the URL of the page you're on (of course add a slash if needed). Also keep the code used to solve this problem!
Here is your input data:
7
-1 156 198 171 134 197 120 149 177 130 100 103 126 169 115 199 188 119 168 151 161 167 141 111
-1 126 128 150 190 193 198 168 128 194 138 196 153 134 163 152 136 158 132 178 141 174 143 195 126 183 132 174 173 171 130 155 164 158
-1 178 115 166 161 164 134 130 164 147 114
1 73 78 81 66 77 0 26 42 48 42 12 24 33 4 54 31 50 34 78 13 21 37 29 85 56 68 12 79 81 82 25 7 16 44 32 82
1 62 35 54 82 30 7 28 78 74 34 12 80 40 16 5 39 29
-1 157 183 175 140 158 164 138 166 176 121 145 139 186 188 158 121 183 146 132 124 123 198 162 135 161 132 187 184 121 148 157 146 123 199 142 134 196 179
-1 70 74 81 105 121 129 148 91 160 76 146 94 64 154 54 102 142 68 62 88 63 144 143 138 118 117 148 166 146 159 162 130 183 184 156 172
Array.max = function( array ){
return Math.max.apply( Math, array );
};
Array.min = function( array ){
return Math.min.apply( Math, array );
};
function m(str) {
var parts = str.split(" ");
var what = parts.shift();
if (what=="-1") return Array.min(parts);
else return Array.max(parts);
}
var num=[];
num.push(7); // not sure about this one. Use the encode if yes
num.push(m("-1 156 198 171 134 197 120 149 177 130 100 103 126 169 115 199 188 119 168 151 161 167 141 111"))
num.push(m("-1 126 128 150 190 193 198 168 128 194 138 196 153 134 163 152 136 158 132 178 141 174 143 195 126 183 132 174 173 171 130 155 164 158"))
num.push(m("-1 178 115 166 161 164 134 130 164 147 114"))
num.push(m("1 1 73 78 81 66 77 0 26 42 48 42 12 24 33 4 54 31 50 34 78 13 21 37 29 85 56 68 12 79 81 82 25 7 16 44 32 82"))
num.push(m("1 62 35 54 82 30 7 28 78 74 34 12 80 40 16 5 39 29"))
num.push(m("-1 157 183 175 140 158 164 138 166 176 121 145 139 186 188 158 121 183 146 132 124 123 198 162 135 161 132 187 184 121 148 157 146 123 199 142 134 196 179"))
num.push(m("-1 70 74 81 105 121 129 148 91 160 76 146 94 64 154 54 102 142 68 62 88 63 144 143 138 118 117 148 166 146 159 162 130 183 184 156 172"))
var str = String.fromCharCode.apply(null, num);
console.log(num,str);
console.log(encodeURIComponent(str)); // if 7 is part of the numbers
// location = "http://www.example.com/"+str;
I use a Golang HTTP request to get json output as follow.
The web service I am trying to access is Micrsoft Translator https://msdn.microsoft.com/en-us/library/dn876735.aspx
//Data struct of TransformTextResponse
type TransformTextResponse struct {
ErrorCondition int `json:"ec"` // A positive number representing an error condition
ErrorDescriptive string `json:"em"` // A descriptive error message
Sentence string `json:"sentence"` // transformed text
}
//some code ....
body, err := ioutil.ReadAll(response.Body)
defer response.Body.Close()
if err != nil {
return "", tracerr.Wrap(err)
}
transTransform = TransformTextResponse{}
err = json.Unmarshal(body, &transTransform)
if err != nil {
return "", tracerr.Wrap(err)
}
I got an error from invalid character 'ï' looking for beginning of value
So, I try to print the body as string fmt.Println(string(body)), it show:
{"ec":0,"em":"OK","sentence":"This is too strange i just want to go home soon"}
It seems the data doesn't have any problem, so I tried to create the same value by jason.Marshal
transTransform := TransformTextResponse{}
transTransform.ErrorCondition = 0
transTransform.ErrorDescriptive = "OK"
transTransform.Sentence = "This is too strange i just want to go home soon"
jbody, _ := json.Marshal(transTransform)
I found the original data might have problem, so I try to compare two data in []byte format.
Data from response.Body:
[239 187 191 123 34 101 99 34 58 48 44 34 101 109 34 58 34 79 75 34 44 34 115 101 110 116 101 110 99 101 34 58 34 84 104 105 115 32 105 115 32 116 111 111 32 115 116 114 97 110 103 101 32 105 32 106 117 115 116 32 119 97 110 116 32 116 111 32 103 111 32 104 111 109 101 32 115 111 111 110 34 125]
Data from json.Marshal
[123 34 101 99 34 58 48 44 34 101 109 34 58 34 79 75 34 44 34 115 101 110 116 101 110 99 101 34 58 34 84 104 105 115 32 105 115 32 116 111 111 32 115 116 114 97 110 103 101 32 105 32 106 117 115 116 32 119 97 110 116 32 116 111 32 103 111 32 104 111 109 101 32 115 111 111 110 34 125]
Any idea how I parse this response.Body and Unmarshal it into data structure?
The server is sending you a UTF-8 text string with a Byte Order Mark (BOM). The BOM identifies that the text is UTF-8 encoded, but it should be removed before decoding.
This can be done with the following line (using package "bytes"):
body = bytes.TrimPrefix(body, []byte("\xef\xbb\xbf")) // Or []byte{239, 187, 191}
PS. The error referring to ï is because the UTF-8 BOM interpreted as an ISO-8859-1 string will produce the characters .
I tried to convert my Go map to a json string with encoding/json Marshal, but it resulted in a empty string.
Here's my code :
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
func main() {
datas := make(map[int]Foo)
for i := 0; i < 10; i++ {
datas[i] = Foo{Number: 1, Title: "test"}
}
jsonString, _ := json.Marshal(datas)
fmt.Println(datas)
fmt.Println(jsonString)
}
My output is :
map[9:{1 test} 2:{1 test} 7:{1 test} 3:{1 test} 4:{1 test} 5:{1 test} 6:{1 test} 8:{1 test} 0:{1 test} 1:{1 test}]
[]
I really don't know where I'm wrong. Thank you for your help.
If you had caught the error, you would have seen this:
jsonString, err := json.Marshal(datas)
fmt.Println(err)
// [] json: unsupported type: map[int]main.Foo
The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using strconv.Itoa.
See this post for more details: https://stackoverflow.com/a/24284721/2679935
It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal.
json: unsupported type: map[int]main.Foo
JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.
You have two options:
1 Use map[string]Foo and convert the index to string (using fmt.Sprint for example):
datas := make(map[string]Foo, N)
for i := 0; i < 10; i++ {
datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)
2 Simply just use a slice (javascript array):
datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)
playground
This behaviour has been changed over time. I am using go v1.16.5 and I can happily pass int type in as JSON key. I have tried the same problem now and I can see the below result. Type conversion of a non-string key has been added by textMarshaler and textUnmarshaler interfaces. For more info, you can visit this https://golang.org/pkg/encoding/json/#Marshal
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
datas := make(map[int]Foo)
for i := 0; i < 5; i++ {
datas[i] = Foo{Number: 1, Title: "test"}
}
jsonString, _ := json.Marshal(datas)
fmt.Println("Datasets Result : ", datas)
fmt.Println("Marshal Datasets Result : ", string(jsonString), err)
m := make(map[int]Foo)
err = json.Unmarshal(jsonString, &m)
if err != nil {
panic(err)
}
fmt.Println("Unmarshal JSON Result : ", m)
Output:
Datasets Result map : [0:{1 test} 1:{1 test} 2:{1 test} 3:{1 test} 4:{1 test}]
Marshal Datasets Result : {"0":{"number":1,"title":"test"},"1":{"number":1,"title":"test"},"2":{"number":1,"title":"test"},"3":{"number":1,"title":"test"},"4":{"number":1,"title":"test"}} <nil>
Unmarshal JSON Result : map[0:{1 test} 1:{1 test} 2:{1 test} 3:{1 test} 4:{1 test}]
data := map[string]interface{}
jsonByte, err := json.Marshal(data)
if err != nil{
log.Fatal(err)
}
jsonString := string(jsonByte)
fmt.Println(jsonString) // will be printing data map in json formate.
Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal would work as expected.
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler
type Num int
func (n *Num) UnmarshalText(text []byte) error {
i, err := strconv.Atoi(string(text))
if err != nil {
return err
}
*n = Num(i)
return nil
}
func (n Num) MarshalText() (text []byte, err error) {
return []byte(strconv.Itoa(int(n))), nil
}
type Foo struct {
Number Num `json:"number"`
Title string `json:"title"`
}
func main() {
datas := make(map[Num]Foo)
for i := 0; i < 10; i++ {
datas[Num(i)] = Foo{Number: 1, Title: "test"}
}
jsonString, err := json.Marshal(datas)
if err != nil {
panic(err)
}
fmt.Println(datas)
fmt.Println(jsonString)
m := make(map[Num]Foo)
err = json.Unmarshal(jsonString, &m)
if err != nil {
panic(err)
}
fmt.Println(m)
}
Output:
map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]
I have a sql table similar to the one below. And I want to bring back unique results where tag_id matches multiple items.
So if I want to find each image_id that has the tag_id = 106 and 73 I would like it to bring back image_id 12345714 and 12345712.
I've tried doing
SELECT *
FROM tag_relationship
WHERE tag_id
IN ( 106, 73 )
But this brings back
id image_id tag_id
61 12345706 73
70 12345712 73
72 12345712 106
76 12345714 73
77 12345714 106
I've also experimented with GROUP BY, but that doesn't seem to be quite right.
Sample of full table:
image_id can have the same number in different rows, but will have a different tag_id.
id image_id tag_id
1 12345679 63
2 12345679 83
3 12345680 74
4 12345680 108
5 12345680 75
6 12345683 103
7 12345682 87
8 12345682 105
9 12345682 74
10 12345682 81
11 12345683 79
12 12345683 109
13 12345689 111
14 12345689 69
15 12345690 104
16 12345687 110
17 12345687 69
18 12345687 91
19 12345687 93
20 12345687 63
21 12345692 69
22 12345692 104
23 12345692 80
24 12345692 76
25 12345693 74
26 12345693 99
27 12345693 96
28 12345693 94
29 12345691 63
30 12345691 69
31 12345697 92
32 12345697 76
33 12345698 74
34 12345699 97
35 12345698 94
36 12345699 98
37 12345698 81
38 12345699 105
39 12345697 91
40 12345694 100
41 12345694 101
42 12345694 94
43 12345694 74
44 12345696 78
45 12345696 95
46 12345696 112
47 12345701 113
48 12345701 114
49 12345700 94
50 12345700 91
51 12345700 90
52 12345702 87
53 12345702 115
54 12345702 80
55 12345702 74
56 12345704 78
57 12345705 83
58 12345705 84
59 12345704 63
60 12345705 104
61 12345706 73
62 12345706 64
63 12345706 86
64 12345706 88
65 12345706 89
66 12345713 80
67 12345713 115
68 12345713 81
69 12345717 63
70 12345712 73
71 12345717 64
72 12345712 106
73 12345717 79
74 12345712 74
75 12345709 76
76 12345714 73
77 12345714 106
78 12345715 68
79 12345716 116
80 12345715 69
81 12345716 71
SELECT image_id
FROM tag_relationship
WHERE tag_id IN ( 106, 73 )
GROUP BY image_id
HAVING COUNT(*) = 2
SELECT DISTINCT image_id
FROM tag_relationship
WHERE tag_id
IN ( 106, 73 )
It might be really stupid/simple, but I think this will work:
SELECT image_id
FROM tag_relationship
WHERE
tag_id = 106 AND tag_id = 73
Try this
SELECT DISTINCT t1.image_id
FROM tag_relationship t1
JOIN tag_relationship t2 ON t1.image_id=t2.image_id
WHERE t1.tag_id=106
and t2.tag_id=73