问题
I have the following code:
public class Continent
{
public string Name { get; set; }
public List<Country> Countries{ get; set; }
}
public class Countries
{
public string Name { get; set; }
public List<Province> Provinces{ get; set; }
}
public class Province
{
public string Name { get; set; }
public List<Province> Cities { get; set; }
}
public class City
{
public string Name { get; set; }
public string Address { get; set; }
}
I want to transform the following query into a lucene query(e.g., Where, Any), so that I get the continents where both Aloma and Hemane are within the same province (and not in distinct provinces) with the respective addresses 123 and 435:
var queryResults = from continent in session
.Advanced.DocumentQuery<Continent>()
from country in continent.Countries
from prov in country.Provinces
let cities_ = prov.Cities
let fi = cities_.Where(fp => fp.Name == "Aloma" && fp.Address == "123").FirstOrDefault()
let fj = cities_.Where(fk => fk.Name == "Hemane" && fk.Address == "435").FirstOrDefault()
where fi != null && fj != null
select continent;
I originally tried the following, but it returns results when Aloma and Hemane are in the same province (what I want), but also when Aloma and Hemane are in distinct provinces (what I don't want):
var queryResultsLucene = session.Advanced.DocumentQuery<Continent>()
.Where("Countries,Provinces,Cities,Name:Aloma")
.AndAlso()
.Where("Countries,Provinces,Cities,Address:123")
.Intersect()
.Where("Countries,Provinces,Cities,Name:Hemane")
.AndAlso()
.Where("Countries,Provinces,Cities,Address:435")
.OfType<Topic>()
.ToList();
Can you please help me? Thanks in advance
回答1:
I would use the Lucene query from my response on RavenDB: how to transform a session.Query into a session.Advanced.DocumentQuery? . I wouldn't use this with a large number of cities though.
var continentsToFindByCity = new List<City>(){new City{Name = "Aloma", Address = "123"}, new City{Name = "Hemane", Address = "435"}};
var results = new List<Continent>();
foreach(var city in continentsToFindByCity)
{
var tempResults = session.Advanced.DocumentQuery<Continent>().Where(
string.Format("Countries,Provinces,Cities,Name: {0} AND Countries,Provinces,Cities,Address: {1}", city.Name, city.Address)).ToList();
if(tempResults.Count > 0)
results.AddRange(tempResults);
}
回答2:
You can use the following query:
var queryResults = session.Advanced.DocumentQuery<Continent>()
.OpenSubClause()
.WhereEquals("Countries,Provinces,Cities.Name", "Aloma")
.AndAlso()
.WhereEquals("Countries,Provinces,Cities.Address", "123")
.CloseSubClause()
.AndAlso()
.OpenSubClause()
.WhereEquals("Countries,Provinces,Cities.Name", "Hemane")
.AndAlso()
.WhereEquals("Countries,Provinces,Cities.Address", "Hemane")
.CloseSubClause()
.ToList();
来源:https://stackoverflow.com/questions/34444396/ravendb-how-to-transform-a-query-into-a-lucene-query