I have the following index created for RavenDB.
public class DayOfMonths_AllDaysSortedByOrder : AbstractIndexCreationTask<DayOfMonth, DayOfMonth>
{
public DayOfMonths_AllDaysSortedByOrder()
{
Map = days => from day in days select new { day };
Sort(x => x.Order, Raven.Abstractions.Indexing.SortOptions.Int);
}
}
However, when I get the documents for this index, they are not returned in proper sorted order. What have I done wrong?
Is it possible that your Map line should be like this?
Map = days => from day in days select new { day.Order };
Related
Is there any way to count the day of booking? either using lambda or sqlite query thanks, can find the solution for a while thanks~
The bookingInput is from a webpage of booking which contains rooms, checkin and check out.
The below code is Create.cshtml.cs in Booking folder (created by scaffolding)
int count = bookingInput.CheckOut.DayOfWeek - booking.CheckIn.DayOfWeek;
booking.Cost = count * theRoom.Price;
You could use the TimeSpan.TotalDays Property to get the number of days between two dates.
Check the following code:
//get data from the Repository.
var result = _repo.GetBookings().Select(c => new
{
Id = c.Id,
Name = c.Name,
RoomNumner = c.RoomNumber,
CheckIn = c.CheckIn,
CheckOut = c.CheckOut,
Days = (c.CheckOut - c.CheckIn).TotalDays,
RoundDays = Math.Round((c.CheckOut - c.CheckIn).TotalDays)
});
The result as below:
The test data in the Repository:
public interface IDataRepository
{
List<BookingViewModel> GetBookings();
}
public class DataRepository : IDataRepository
{
public List<BookingViewModel> GetBookings()
{
return new List<BookingViewModel>()
{
new BookingViewModel(){ Id=101, Name="David", RoomNumber=1001, CheckIn= new DateTime(2021,1,18,15,30,0), CheckOut=DateTime.Now },
new BookingViewModel(){ Id=102, Name="Jack", RoomNumber=2001, CheckIn= new DateTime(2021,1,15,10,30,0), CheckOut=DateTime.Now },
new BookingViewModel(){ Id=103, Name="Tom", RoomNumber=3001, CheckIn= new DateTime(2021,1,20,18,30,0), CheckOut=DateTime.Now },
};
}
}
My application has a requirement that is should be able to filter/search for Pairs by the Number of the related Contact.
A Pair always has a reference to a Contact stored, but the number of the contact is not, and will not, be stored in the reference. So I tried to create a custom index for this, because the Pair and Contact are stored in different collections.
A simplified example of the index looks like this.
public class Pairs_Search : AbstractMultiMapIndexCreationTask<Pairs_Search.Result>
{
public class Result
{
public string Id { get; set; }
public string Workspace { get; set; }
public ContactResult Contact { get; set; }
public bool HasContactDetails { get; set; }
}
public class ContactResult
{
public string Id { get; set; }
public string Name { get; set; }
public int Number { get; set; }
}
public Pairs_Search()
{
AddMap<Pair>(pairs => pairs
.Select(p => new
{
p.Id,
p.Workspace,
Contact = new
{
p.Contact.Id,
p.Contact.Name,
Number = 0
},
// Mark this items as WITHOUT contact details.
HasContactDetails = false,
}
)
);
AddMap<Contact>(contacts => contacts
.Select(c => new
{
Id = (string) null,
Workspace = (string) null,
Contact = new
{
c.Id,
Name = c.DisplayName,
c.Number
},
// Mark this items as WITH contact details.
HasContactDetails = true,
}
)
);
Reduce = results => results
// First group by the contact ID. This will
// create a group with 2 or more items. One with the contact
// details, and one or more with pair details.
// They are all marked by a boolean flag 'HasContactDetails'.
.GroupBy(x => x.Contact.Id)
// We are going to enrich each item in the current group, that is
// marked as 'HasContactDetails = false', with the contact number.
// We need that so that we can filter on it later.
.Select(group =>
group
.Select(i => new
{
i.Id,
i.Workspace,
Contact = new
{
i.Contact.Id,
i.Contact.Name,
// Does the current item have the contact details?
Number = i.HasContactDetails
// Yes, in this case we use the previously set contact number.
? i.Contact.Number
// No, find the item with the contact details and grab the number.
: group.Single(x => x.HasContactDetails).Contact.Number
},
// Pass on the flag that indicates wheter or not
// this item has the contact details. We are going
// to need it later.
i.HasContactDetails
}
)
// We don't need the items with the contact details
// anymore, so filter them out.
.Where(x => !x.HasContactDetails)
)
// Flatten all the small lists to one big list.
.SelectMany(x => x);
// Mark the following fields of the result as searchable.
Index(x => x.Contact.Number, FieldIndexing.Search);
}
}
I've setup a full example that reproduces the issues I am having. You can find the example here.
Creating the index works fine. Querying the index works fine also as it properly matched the pair and contact and enriched the index result with the number of the contact. But when I try to use a .Where() or .Search() on the nested Number property it fails to properly filter the result dataset from the index.
The index without any filtering works as you can see in below code example (also available in the full example).
private static async Task ThisOneWorks()
{
using (var session = Store.OpenAsyncSession())
{
var results = await session
.Query<Pairs_Search.Result, Pairs_Search>()
.ToListAsync();
LogResults("ThisOneWorks()", results);
}
// Output:
// ThisOneWorks(): Pair 'Harry Potter' with number '70'
// ThisOneWorks(): Pair 'Harry Potter' with number '70'
// ThisOneWorks(): Pair 'Hermione Granger' with number '71'
// ThisOneWorks(): Pair 'Albus Dumbledore' with number '72'
}
Filtering on a non-nested value also works (also available in the full example). As you can see it filters out the one with a different workspace.
private static async Task ThisOneWithWorkspaceFilterWorks()
{
using (var session = Store.OpenAsyncSession())
{
var results = await session
.Query<Pairs_Search.Result, Pairs_Search>()
.Where(x => x.Workspace == "hogwarts")
.ToListAsync();
LogResults("ThisOneWithWorkspaceFilterWorks()", results);
}
// Output:
// ThisOneWithWorkspaceFilterWorks(): Pair 'Harry Potter' with number '70'
// ThisOneWithWorkspaceFilterWorks(): Pair 'Harry Potter' with number '70'
// ThisOneWithWorkspaceFilterWorks(): Pair 'Hermione Granger' with number '71'
}
When I try to filter/search on the Workspace and Number properties I would expect two results that are related to the contact Harry Potter. But instead I just get an empty dataset back.
private static async Task ThisOneWithWorkspaceAndNumberFilterDoesntWork()
{
using (var session = Store.OpenAsyncSession())
{
var results = await session
.Query<Pairs_Search.Result, Pairs_Search>()
.Where(x => x.Workspace == "hogwarts")
.Where(x => x.Contact.Number == 70)
.ToListAsync();
LogResults("ThisOneWithWorkspaceAndNumberFilterDoesntWork()", results);
}
// Output:
// ThisOneWithWorkspaceAndNumberFilterDoesntWork(): EMPTY RESULTS!
}
Can anyone tell me what I am doing wrong here? Any help would be greatly appreciated!
The way to go about it is to store ContactResult in a different collection,
which is what is called a related document in this case,
and when you create the index then you 'Index the Related Document'
Learn from the demo example in:
https://demo.ravendb.net/demos/csharp/related-documents/index-related-documents
The example is for a basic map index but the principle is the same for Multi-Map.
Remove the public class ContactResult from the index class
and define the index with something like:
select new Result
{
....
Number = LoadDocument<Contact>(Pair.Contact).Number
....
}
Im using the latest build of RavenDB (3.0.3800)
When I run a simple query with a Search and Orderby the Search is ignored. If I remove the OrderBy the Search works and returns the correct results
var query = _session.Query<Index_All.ReduceResult, Index_All>()
.Customize(x => x.WaitForNonStaleResults())
.Search(x => x.SearchTerm, "Some String")
.OrderBy(x => x.PublishDate);
This just returns all results, ignoring my Search completely.
Here is my Index:
public class Index_All : AbstractIndexCreationTask<MyDocuemnt,Index_All.ReduceResult>
{
// query model
public class ReduceResult
{
public string SearchTerm { get; set; }
public DateTimeOffset PublishDate { get; set; }
}
public Index_All()
{
Map = documents => from d in documents
let customer = LoadDocument<Customer>(d.Customer.Id)
let owner = LoadDocument<Customer>(d.Owner.Id)
select new
{
SearchQuery = new object[]
{
customer.Name,
owner.Name,
},
d.PublishDate,
};
Index(x => x.SearchTerm, FieldIndexing.Analyzed);
}
}
I have no idea why this is happening, the only work around i have is to return the result unordered. Can anyone spot what the problem is here ?
Thanks
You probably don't want the orderby to work. The result of a [full text] Search is going to be ordered by Lucene score. That's going to give you the best matches for the search terms provided by the user. Given that, ordering by publish date would "ruin" the quality of the results.
However, I just tried this with v30k, and it appears to use the order by properly after filtering using Search.
Edit - I notice you're using "SearchTerm" for the query model and the analyze expression, but you're indexing "SearchQuery". Make those the same and it should work.
When I add the index below to my raven database a simple query like
return Session.Query<R>().FirstOrDefault(x => x.RId == Id);
Always returns null. Only after forcing Raven to remove my custom index does desired functionality return. Why is this?
The Index with side effects:
public class RByLatestCommentIndex : AbstractIndexCreationTask<R>
{
public RByLatestCommentIndex()
{
SetMap();
}
void SetMap()
{
Map = r => r.Select(x => new
{
Id = x.Id,
TimeStamp = x.Comments.Count() > 0 ? x.Comments.Max(u => u.Created)
: x.Created
}).OrderByDescending(y => y.TimeStamp).Select(r => new { Id = r.Id });
}
}
public class RIdTransformer : AbstractTransformerCreationTask<R>
{
public RIdTransformer()
{
TransformResults = ids => ids.Select(x => LoadDocument<R>(x.Id));
}
}
EDIT:
In response to Ayende Rahien's comment:
There's a query in the DB which would otherwise be used (Auto/R/ByRID) but the index used looks like this, puzzling enough:
from doc in docs.Rs select new { Images_Count__ = doc.Images["Count()"], RId = doc.RId }
What explains this behaviour? And, will I have to add a static index to be able to query R by RId ?
In my database I have a list of cases:
{ Id: 1, Owner: "guid1", Text: "Question1" }
{ Id: 2, Owner: "guid1", Text: "Question2" }
{ Id: 3, Owner: "guid2", Text: "Question3" }
When querying for data I would also like to have (in my index, result) number of cases each Owner has. So I created a map/reduce index on this collection:
public class RelatedCases
{
public Guid Owner { get; set; }
public int Count { get; set; }
}
public class RelatedCaseIndex : AbstractMultiMapIndexCreationTask<RelatedCases>
{
public RelatedCaseIndex()
{
AddMap<CaseDocument> (c => c.Select(a => new { a.Owner, Count = 1 }));
Reduce = result => result
.GroupBy(a => a.Owner)
.Select(a => new
{
Owner = a.Key,
Count = a.Sum(b => b.Count)
});
}
}
Now I just have no idea how to produce a query to include the data from the index. Based on documentation I tried something like:
session.Query<CaseDocument>().Customize(a => a.Include ...)
or TransformResults on a CaseIndex, which didn't work out properly.
I know I could just requery raven to get me list of all RelatedCases in a separate query, but I would like to do it in one round-trip.
You can't query for Cases and join the result with the map/reduce index on the fly. That's just not how it works, because every query will run against an index, so what you are really asking is joining two indexes. This is something you need to do upfront.
In other words - put all the information you want to query upon into your map/reduce index. You can then run the query on this index and .Include() the documents that you are also interested in.
I dont think you need a MultiMap index, a simple MapReduce index will suffice for this.
You can then query it like so:
session.Query<RelatedCases, RelatedCaseIndex>();
This will bring back a list of RelatedCases with the owner and count.