Search code examples
c#nestedravendbdocuments

RavenDB: how to transform a session.Query into a session.Advanced.DocumentQuery?


I stored the objects of the following classes in a ravendb database:

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; }
}

Thanks to a post (RavenDB: how to retrieve the top nodes in a nested collection?) I have learned how to use session.Query to retrieve from the database all the continents having cities with Name and Address respectively set to "aloma" and "123". I would like to write the same query using session.Advanced.DocumentQuery. So can you please tell me how to transform the following query into a session.Advanced.DocumentQuery: var continents = session.Query() .Where(x=>x.Countries.Any(country => country.Provinces.Any(p=>p.Cities.Any(city => city.Name == "123" && city.Address == "aloma"))).OfType().ToList(); ?


Solution

  • Note, this is probably not the best way to do this but it's the only way I know how. Also, note the following will create an index once executed.

    var results = session.Advanced.DocumentQuery<Continent>().Where("Countries,Provinces,Cities,Name: 123 AND Countries,Provinces,Cities,Address: aloma").ToList();
    

    Model structure used:

        public class Continent
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public List<Country> Countries { get; set; }
    }
    
    public class Country
    {
        public string Name { get; set; }
        public List<Province> Provinces { get; set; }
    }
    
    public class Province
    {
        public string Name { get; set; }
        public List<City> Cities { get; set; }
    }
    
    public class City
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }