I have a RavenDB 3.5 collection "Municipalities" with documents structured like this:
{
"Name": ...,
...,
"Districts": [
{
"Name": ...,
...
}
]
}
Note that the districts property can also be null.
Now I'm working on a typehead feature where you can search for both municipality names and district names. So I want to (wildcard all) query over both fields and also get back the value that was matched. So I don't want the whole document because if the match was on a district name, I can't easily return that value.
I've tried several options with .Search()
and .Suggest()
but couldn't quite get there.
In order to search on both the municipality names and district names you can build an MultiMap index which would map the name from same collection twice, once from the municipality name and once it would fan out on the districts name.
The result of the query on the index would be the document which holds all of the data. In order to get a specific result from the index you can store the data you want to retrieve inside the index. This way only the intended data would return and not the all document.
public class MunicipalitiesAndDistrictsNamesIndex : AbstractMultiMapIndexCreationTask<MunicipalitiesAndDistrictsNamesIndex.Result>
{
public class Result
{
public string Name { get; set; }
public string Value { get; set; }
}
public MunicipalitiesAndDistrictsNamesIndex()
{
AddMap<Municipality>(municipality => from m in municipalities
select new
{
m.Name,
m.Value,
});
AddMap<Municipality>(municipality => from m in municipalities
from d in m.Districts
select new
{
d.Name,
d.Value,
});
// mark 'Name' field as analyzed which enables full text search operations
Index(x => x.Name, FieldIndexing.Search);
// storing fields so when projection
// requests only those fields
// then data will come from index only, not from storage
Store(x => x.Name, FieldStorage.Yes);
Store(x => x.Value, FieldStorage.Yes);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With