I need to take the results of a query:
var query = from m in db.SoilSamplingSubJobs where m.order_id == id select m;
and prepare as an ICollection so that I can have something like
ICollection<SoilSamplingSubJob> subjobs
at the moment I create a list, which isnt appropriate to my needs:
query.ToList();
what do I do - is it query.ToIcollection() ?
List is an ICollection. You can change you query.ToList() code to the following.
query.ToList() as ICollection<SoilSamplingSubJob>;
You question sounds like this query is returned as a function result. If this is the case remember that the Linq to SQL objects are connected by default so you will need to manage where your database context get opened and closed. Alternatively you can create DTOs (Data Transfer Objects) that hold the data you want to use in the rest of your program. These objects can fit into your object hierarchy any way you want.
You can also create these DTOs as part of the query.
var query = from m in db.SoilSamplingSubJobs where m.order_id == id
select new SubJobDTO {
OrderNumber = m.order_id
};
return query.ToList() as ICollection<SubJobDTO>;
Since, query implements IEnumerable, you can pass it to the constructor of the collection of your choice. ICollection is an interface, implemented by several classes (including List<T>, which ToList returns) with different performance characteristics.
With slightly different syntax, you can do something like this as well that can cut down on what goes into the ICollection. This type of approach is great for Angular and MVC when you have a huge table but only want to load some props into the cshtml page:
ICollection<SoilSamplingSubJob> samples = dbContext.GetQuery().Where(m => m.order_id == id)
.AsEnumerable().Select(s => new
{
Id = s.order_id,
CustomProperty = s.some_thing
}).ToList() as ICollection<SoilSamplingSubJob>
Related
I am currently testing how to design a query from AWS.DynamoDB.DocumentClient query() call that takes params: DocumentClient.QueryInput, which is used for retrieving data collection from a table in DynamoDB.
Query seems to be simple and working fine while working with indexes of type String or Number only. What I am not able to make is an query, that will use a valid index and filter upon an attribute that is nested (see my data structure please).
I am using FilterExpression, where can be defined logic for filtering - and that seems to be working fine in all cases except cases when trying to do filtering on nested attribute.
Current parameters, I am feeding query with
parameters {
TableName: 'myTable',
ProjectionExpression: 'HashKey, RangeKey, Artist ,#SpecialStatus, Message, Track, Statistics'
ExpressionAttributeNames: { '#SpecialStatus': 'Status' },
IndexName: 'Artist-index',
KeyConditionExpression: 'Artist = :ArtistName',
ExpressionAttributeValues: {
':ArtistName': 'BlindGuadian',
':Track': 'Mirror Mirror'
},
FilterExpression: 'Track = :Track'
}
Data structure in DynamoDB's table:
{
'Artist' : 'Blind Guardian',
..
'Track': 'Mirror Mirror',
'Statistics' : [
{
'Sales': 42,
'WrittenBy' : 'Kursch'
}
]
}
Lets assume we want to filter out all entries from DB, by using Artist in KeyConditionExpression. We can achieve this by feeding Artist with :ArtistName. Now the question, how to retrieve records that I can filter upon WritenBy, which is nested in Statistics?
To best of my knowledge, we are not able to use any other type but String, Number or Binary for purpose of making secondary indexes. I've been experimenting with Secondary Indexes and Sorting Keys as well but without luck.
I've tried documentClient.scan(), same story. Still no luck with accessing nested attributes in List (FilterExpression just won't accept it).
I am aware of possibility to filter result on "application" side, once the records are retrieved (by Artists for instance) but I am interested to filter it out in FilterExpression
If I understand your problem correctly, you'd like to create a query that filters on the value of a complex attribute (in this case, a list of objects).
You can filter on the contents of a list by indexing into the list:
var params = {
TableName: "myTable",
FilterExpression: "Statistics[0].WrittenBy = :writtenBy",
ExpressionAttributeValues: {
":writtenBy": 'Kursch'
}
};
Of course, if you don't know the specific index, this wont really help you.
Alternatively, you could use the CONTAINS function to test if the object exists in your list. The CONTAINS function will require all the attributes in the object to match the condition. In this case, you'd need to provide Sales and WrittenBy, which probably doesn't solve your problem here.
The shape of your data is making your access pattern difficult to implement, but that is often the case with DDB. You are asking DDB to support a query of a list of objects, where the object has a specific attribute with a specific value. As you've seen, this is quote tricky to do. As you know, getting the data model to correctly support your access patterns is critical to your success with DDB. It can also be difficult to get right!
A couple of ideas that would make your access pattern easier to implement:
Move WrittenBy out of the complex attribute and put it alongside the other top-level attributes. This would allow you to use a simple FilterExpression on the WrittenBy attribute.
If the WrittenBy attribute must stay within the Statistics list, make it stand alone (e.g. [{writtenBy: Kursch}, {Sales: 42},...]). This way, you'd be able to use the CONTAINS keyword in your search.
Create a secondary index with the WrittenBy field in either the PK or SK (whichever makes sense for your data model and access patterns).
Using Sitecore 8.2 with MVC.
I'm trying to implement the search functionality in a MVC view. (with a textbox and submit button)
There is a folder in the content tree called Books which has a list of items. Each item will have these fields - Title, Author, Price
When user searches for a term, it will be checked for a match with any of the 3 fields of the item and return the results.
This method is not working as it returns null Item.
public PartialViewResult GetSearchBooks(string txtSearch)
{
string index = string.Format("sitecore_{0}_index", Sitecore.Context.Database.Name);
List<SearchResultItem> query;
List<Item> matches = new List<Item>();
using (var context = ContentSearchManager.GetIndex(index).CreateSearchContext())
{
query = context.GetQueryable<SearchResultItem>()
.Where(p => p.Path.StartsWith("/sitecore/content/Book")).ToList();
}
foreach(SearchResultItem sritem in query)
{
Item item = sritem.GetItem(); //item is null here
if(item.Fields["Title"].Value.Contains(txtSearch) ||
item.Fields["Title"].Value.Contains(txtSearch) ||
item.Fields["Title"].Value.Contains(txtSearch))
matches.Add(item);
}
return(matches);
}
Is it the right approach. If not please suggest one.
Paths
Avoid querying the path like this:
context.GetQueryable<SearchResultItem>()
.Where(p => p.Path.StartsWith("/sitecore/content/Book"));
Instead use
context.GetQueryable<SearchResultItem>()
.Where(p => p.Paths.Contains(idOfBookFolderItem));
For more info on why, see http://blog.paulgeorge.co.uk/2015/05/29/sitecore-contentsearch-api-filtering-search-on-folder-path/
Approach
You need to hand the entire query to the search api in one go.
List<SearchResultItem> matches;
using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext())
{
var predicate = PredicateBuilder.True<SearchResultItem>();
// must have this (.and)
predicate = predicate.And(p => p.Paths.Contains(bookFolderItem.ID));
// must have this (.and)
predicate = predicate.And(p => p.Name == searchTerm);
matches = context.GetQueryable<SearchResultItem>().Where(predicate).ToList();
}
This returns SearchResultItems not Items. If you need the item, just call GetItem.
Matches[i].GetItem()
Null items
This may indicate that your index is out of sync with the database. Try re-indexing from control panel, or in the case of the web database, REpublish the expected content.
Searching template fields
This just searches against the item name. You're limited to being able to specify the generic fields in SearchResultItem class. If you want to search specific fields on items, you can inherit from SearchResultItem and add those fields.
public class BookSearchResultItem : SearchResultItem
{
[IndexField("Book Title")]
public string BookTitle { get; set; }
[IndexField("Book Author")]
public string BookAuthor { get; set; }
}
You can then pass this into the query and search on those fields
List<BookSearchResultItem> matches;
using (var context = ContentSearchManager.GetIndex(indexName).CreateSearchContext())
{
var predicate = PredicateBuilder.True<BookSearchResultItem>();
// must have this (.and)
predicate = predicate.And(p => p.Paths.Contains(bookFolderItem.ID));
// must have this (.and)
predicate = predicate.And(
PredicateBuilder.False<BookSearchResultItem>() // in any of these fields
.Or(p => p.BookTitle == searchTerm)
.Or(p => p.BookAuthor == searchTerm)
.Or(p => p.Name == searchTerm));
matches = context.GetQueryable<BookSearchResultItem>().Where(predicate).ToList();
}
Searching all 'content'
If you find that having to specify the explicit fields is an unwanted hassle or you are performing searches across different templates with different fields, you can instead use the special computed 'content' field which combines all the text data from an item into one indexed field. So instead of the original query which did this
predicate = predicate.And(p => p.Name == searchTerm);
You can instead do just use
predicate = predicate.And(p => p.Content == searchTerm);
Which will find results where the searchterm exists in any field on the item.
First, did you check "query" contains any result?
I would suggest performing the following search query:
query = context.GetQueryable<SearchResultItem>()
.Where(p => p.TemplateId == yourBookItemTemplateID &&
(p.Fields["Title"].Value.Contains(txtSearch) ||
p.Fields["Author"].Value.Contains(txtSearch) ||
p.Fields["Price"].Value.Contains(txtSearch));
return query.Select(x => x.GetItem());
i would not suggest this approach to use. Let me explain why, or what you can do better.
First create your own Sitecore index and do not simply use the default master or web index. If you do that, you can safe the following line of code .Where(p => p.Path.StartsWith("/sitecore/content/Book")).ToList();, cause in a custom index you can simply restrict, what exactly is crawled.
Second you should never access the Sitecore item out of the search results. Reasons for that is the performance. Item item = sritem.GetItem(); You use a search, because its a performant way to access a huge amount of data. When you now access for every result the Sitecore item from the database, you lose your benefit of using a search.
You should simply use the Result Type, in your case the basic SearchResultItem. At the End of your filtering you should call something like var results = query.GetResults(); instead of accessing the items directly.
Here I found a simple example of a sitecore search, with custom index and without accessing the items directly, maybe this helps you.
http://www.mattburkedev.com/sitecore-7-contentsearch-tips/
Now to your problem.
Did you debug the search and looked into the rest of the fields of sritem? Are they all filled? If i remember correctly there is a property which stores the itemId, to retrieve the item with GetItem(). Maybe you could give us the values of the property while trying to retrieve the item.
Sometimes when the index is out of date, the returned search items may no longer exist in your content tree, So rebuild the index and try the search again,
Couple of enhancements that you can apply to your search:
As mentioned in Christian answer you can create index for just your Books tree, which means to set the root of the index to the Books root item.Web index usually used for full site content search.
Instead of getting all books items then go through all items; you can use predicates instead; even after you create the new index use the predicates to get the desired items only.
Also if your site is multilingual add a predicate to filter the required language else you will get multiple versions of the same item.
When querying, ActiveRecord automagically decides how to handle ranges, arrays, etc. based on column type.
Now what I want to do is query an integer column for a set of bit values by calling something like Model.where(bitfield: [1,4,16,32]).count where it will build a query accordingly, counting all objects that have at least one of those bits set.
I already know how to build the resulting SQL, I'm looking for a place to put my code that will basically check for the column type, find out I configured it to be bitfield and use my handler to build the relevant SQL parts.
My first thought would be to make a bit_where method in your model which is bitfield-aware...
class Model << ActiveRecord::Base
BITFIELDS = [:bitfield]
def self.bit_where(*args, options={})
bitfield_options = {}
options.each do |k, v|
if BITFIELDS.include?(k)
bitfield_options[k] = v
options.delete(k)
end
end
collection = self.where(*args, options) # the regular "where" query
bitfield_options.each do |k, v|
... collection.where( custom sql here based on each key, value )
end
collection
end
Is there any way to sort the following items according to the days of week.
In C# I can do something like this:
string [] initialArray = {"Friday", "Monday", ... } ;
string [] sortedArray = initialArray.OrderBy(s => Enum.Parse(typeof(DayOfWeek), s)).ToArray() ;
But I don't know how can I achieve this kind of functionality with Sitecore.
If what you really care is to display the days sorted on the front-end regardless of how they are organised in the Content Editor then simply sort them in code before you display them, e.g.
using System.Linq;
var openingHours = Sitecore.Context.Item.Children
.OrderBy(s => Enum.Parse(typeof(DayOfWeek), s.DisplayName));
If you want to sort them in the Content Editor then you need to create a custom sorter. Sitecore Climber has provided links, but for this specific example you can use:
using Sitecore.Data.Comparers;
using Sitecore.Data.Items;
public class DayOfWeekComparer : Comparer
{
protected override int DoCompare(Item item1, Item item2)
{
var x = (int)Enum.Parse(typeof(DayOfWeek), item1.DisplayName);
var y = (int)Enum.Parse(typeof(DayOfWeek), item2.DisplayName);
return x.CompareTo(y);
}
}
Then in the core database create an item of item type /sitecore/templates/System/Child Sorting under /sitecore/system/Settings/Subitems Sorting and set the type to your class.
You should set the Subitem Sorting on the Standard values of a template. In this instance it looks like you have a simple Folder template, so you would need to create a more specific template for your Opening Hours folder. Even so, the user can still decide to re-order the items OR change the default sort for that folder. The only guaranteed way to force the output is by sorting before you render, i.e. the first bit of code.
please check next articles:
http://firebreaksice.com/how-to-sort-sitecore-items-in-the-content-editor/
http://sitecore.alexiasoft.nl/2009/08/04/sorting-sitecore-items/
http://sitecoreblog.blogspot.in/2010/11/change-default-subitems-sort-order.html
In JPA1 you could map a result to a non-managed entity by something like this:
Query query = entityManager.createQuery("SELECT NEW com.test.TestInfo(e.name, e.city) from Example e");
In JPA2 you could do it like this :
Query query = entityManager.createQuery(“SELECT e.name, e.city from Example e”,TestInfo.Class);
How would I do that with the criteria-api? I simply don't know the buzzwords to google for.
Any hints?
Jonny
That can be done via CriteriaBuilder.construct. First argument is class of result, following arguments are Selections.