Reputation: 581
I need to search a string value in every fields in source. So if my string "queryValue" is "test" and I have in my index something like:
"hits": [
{
"_index": "sql-data",
"_type": "_doc",
"_id": "jTI5kHMBal-9d-PPo5Kr",
"_score": 1.0,
"_source": {
"Id": 57,
"object1": [
{
"description": "test",
}
],
"object2": [
{
"description": "nomore",
}
],
}
]
I want to get this hit back from my query because description of object1 is test. Thats my code, actually returns every hits in my index and not only the matched:
var searchResponse = client.SearchAsync<Document>(s => s
.Source(sf => sf
.IncludeAll())
.Query(p => p
.Match(s => s
.Query(queryValue)
)))
.Result;
Upvotes: 0
Views: 1693
Reputation: 1404
There are multiple ways to do this. But the feasibility of each of these depends on how you actually implemented your mapping.
The data under _all field is only indexed and not stored. Hence, you can only search for the data but cannot retrieve it. Using _all
comes with its own limitations as the data is first concatenated into a string and then analyzed and indexed. Hence, things like partial matching or any specific analyzer behaviour may not be possible. To achieve this, you may need to specify a custom analyzer for overriding this behaviour. This might actually bloat your index. Above all, you should have _all
field enabled at the time of indexing. Unless there is a very strict requirement and using an older version of ES, it is better not going down this route. This is deprecated in version 6.0 and removed in version 7.0
Multi-match of elasticsearch allows us to build match queries that match that multiple fields. You can specify all the fields that you'd want to search on inside the query DSL. You can create a method as shown below that does a multi match usage.
private static QueryContainer BuildMultiMatchQuery(string queryValue)
{
return new QueryContainerDescriptor<Document>()
.MultiMatch(c => c
.Fields(f => f
.Field(doc => doc.Field1)
.Field(doc => doc.Field2)
// other fields)
.Query(queryValue)
// Add other properties and configuration like analyzers you need, in this block
);
}
This can be added to your searchAsync call chain in the way shown below
var searchResponse = client.SearchAsync<Document>(s => s
// ...other code
.Query(BuildMultiMatchQuery(queryValue))
// ...other code
).Result;
Read about multi-match
query from here and about _all
from here
You may also want to take a look at copy_to
Upvotes: 1