I am new in elasticsearch and I need to write query described below
I have an elasticsearch index with documents like this one
Numbers mean entries of words in book
JavaScript
x
8
1
{
2
"words": { # words listed below are different in every document
3
"cat": 7,
4
"monkey": 4,
5
"mouse": 10,
6
7
}
8
I want to search documents by words “cats” (not “cat”), “monkey” and e.g “mous”. How do I write query that will find “cat”, “monkey” and “mouse” in document and consider their values in counting score?
upd. Example: I have documents
JavaScript
1
26
26
1
{ # doc1
2
"words": {
3
"cat": 7,
4
"monkey": 4,
5
"mouse": 10,
6
}
7
}
8
{ # doc2
9
"words": {
10
"Cat": 20,
11
"monkeys": 40,
12
"mouse": 10,
13
}
14
}
15
{ # doc3
16
"words": {
17
"Dog": 10,
18
"monkey": 2,
19
"human": 10,
20
}
21
}
22
# I am searching by words "cats", "monkey", "mouse"
23
# I want to get doc2 as the most relevant result (because of words matches and entries quantity).
24
# doc1 should be the second result (words do match, but there are less entries).
25
# doc3 is the third result (too few words matches)
26
Any ideas?
Advertisement
Answer
I don’t know if I understand correctly but you want to search for “cats” and return the doc words with the words “cat”, “monkey” and “mouse”.
Run this example I made and see if it works for you.
JavaScript
1
48
48
1
PUT my-index-000001
2
{
3
"mappings" : {
4
"properties" : {
5
"words" : {
6
"properties" : {
7
"count" : {
8
"type" : "text"
9
},
10
"key" : {
11
"type" : "text",
12
"analyzer": "english"
13
}
14
}
15
}
16
}
17
}
18
}
19
20
POST my-index-000001/_doc/1
21
{
22
"words": [
23
{
24
"key": "cat",
25
"count": "7"
26
},
27
{
28
"key": "monkey",
29
"count": "4"
30
},
31
{
32
"key": "mouse",
33
"count": "10"
34
}
35
]
36
}
37
38
GET my-index-000001/_search
39
{
40
"query": {
41
"match": {
42
"words.key":{
43
"query": "cats"
44
}
45
}
46
}
47
}
48