问题
Below is the sample data in elasticsearch
PUT /data/test/1
{
"id": "Accounting 101",
"room": "E3",
"professor": {
"name": "Thomas Baszo",
"email": "baszot@onuni.com"
},
"students_enrolled": 27,
"course_description": " financial statements"
}
PUT /data/test/2
{
"name": "Accounting 101",
"room": "E3",
"professor": {
"name": "Sachin Baszo",
"email": "baszot@onuni.com"
},
"students_enrolled": 27,
"course_description": "Thomas Thomas Thomas Thomas "
}
Below is the query
GET /_search
{
"query": {
"query_string": {
"query": "(*Thomas*)"
}
}
}
My output will show second document as first as it contains "Thomas" 4 times in the description
- I need to give more weightage to
professor.name
it should show first check if not then check "professor.email" then check other attributes
Python
es.search(index="data", body={"query": {"query_string": {"query": "(*Thomas*)"}}})
回答1:
It is not recommended to use query_string
, as mentioned in the ES official documentation:
Because it returns an error for any invalid syntax, we don’t recommend using the query_string query for search boxes.
If you don’t need to support a query syntax, consider using the match query. If you need the features of a query syntax, use the simple_query_string query, which is less strict.
You can use Boost where
Individual fields can be boosted automatically — count more towards the relevance score — at query time
Adding a working example with index mapping, search query, and search result
Index Mapping:
{
"mappings": {
"properties": {
"professor": {
"properties": {
"name": {
"type": "text",
"boost": 2
}
}
}
}
}
}
Search Query:
{
"query": {
"multi_match" : {
"query": "Thomas",
"fields": [ "course_description", "professor.name" ]
}
}
}
Search Result:
"hits": [
{
"_index": "stof_63933144",
"_type": "_doc",
"_id": "1",
"_score": 1.3862942, <-- note this
"_source": {
"id": "Accounting 101",
"room": "E3",
"professor": {
"name": "Thomas Baszo",
"email": "baszot@onuni.com"
},
"students_enrolled": 27,
"course_description": " financial statements"
}
},
{
"_index": "stof_63933144",
"_type": "_doc",
"_id": "2",
"_score": 1.1090355, <-- note this
"_source": {
"name": "Accounting 101",
"room": "E3",
"professor": {
"name": "Sachin Baszo",
"email": "baszot@onuni.com"
},
"students_enrolled": 27,
"course_description": "Thomas Thomas Thomas Thomas "
}
}
]
Update 1:
Search query for searching for Thomas
OR Sachin
{
"query": {
"multi_match" : {
"query": "(Thomas) OR (Sachin)",
"fields": [ "course_description", "professor.name" ]
}
}
}
Update 2:
Multi match query using "operator":"OR"
{
"query": {
"multi_match" : {
"query": "Thomas Sachin",
"fields": [ "course_description", "professor.name" ] ,
"operator":"OR",
"type":"cross_fields"
}
}
}
来源:https://stackoverflow.com/questions/63933144/how-to-give-more-weightage-for-one-attributes-in-dsl-query-search-string