I need to implement this query in solrJ
&sort=query($manu_sort,0) desc, query($manu_service_sort,0) desc, query($seller_sort,0) desc, _s_name asc, sku asc &manu_sort=ManufacturerName:"Service Champ" &manu_service_sort=ManufacturerName:"SERVICE CHAMP" &seller_sort=BestSeller:true
when I directly add to my code like
customSort = "&sort=query($manu_sort,0) desc, query($manu_service_sort,0) desc, query($seller_sort,0) desc, _s_name asc, sku asc &manu_sort=ManufacturerName:"Service Champ" &manu_service_sort=ManufacturerName:"SERVICE CHAMP" &seller_sort=BestSeller:true";
queryQ = queryQ+customSort;
solrQuery.setQuery(queryQ);
QueryResponse e = this.provider.get(this).query(solrQuery, METHOD.POST);
this throws error like
no field name specified in query and no default specified via 'df' param
can any one help?
I could not get your query...but can suggest a sample code which could be of help to you.
String solrUrl = "http://localhost:8983/solr/";
HttpSolrClient httpSolrClient = new HttpSolrClient.Builder(solrUrl).build();
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
query.set("defType","edismax");
//query.set("qf","file_name^10 content_text^1");
query.addFilterQuery("name : abcdef");
//sorting & direction
query.addSort("Name_of_field_For_sorting", SolrQuery.ORDER.desc);
// set the debug
//query.set("debug", "true");
//for faceting
//query.setFacet(true);
//query.addFacetField("name_of_the_Field")
//query.setFacetLimit(10);
//set the fields
query.setFields(new String[] {"id", "name"});
// for highlighting
query.setHighlight(true);
query.addHighlightField("Name_of_field_to_be_Highlighted");
query.addHighlightField("content_text");
query.setHighlightSimplePre("<hlt>");
query.setHighlightSimplePost("</hlt>");
query.setHighlight(true).setHighlightSnippets(2);
query.setHighlightFragsize(150);
query.setStart(0);
query.setRows(10);
QueryResponse response = httpSolrClient.query(query);
SolrDocumentList results = response.getResults();
//iterate the results
for (int i = 0; i < results.size(); ++i) {
System.out.println(results.get(i));
}
The other try could be something like below.
SolrQuery query = new SolrQuery();
String nested = "";
nested += "Field_name:";
nested += "Field_Value";
nested += " AND _query_:\"{!dismax qf=Field_name1=";
nested += "Field_Value1";
nested += "}\"";
query.setQuery(nested);
String fieldList = "id,name,category";
query.set("fl", fieldList);
QueryResponse response = httpSolrClient.query(query);
Related
Hello I'm trying to copy the following linq results to a datatable. The only examples I see of copytodatatable is using the query format, and not the extension methods. Wondering if anyone knows how to use it with the extension methods (I've tried casting the results to IEnumerable datarow but it didn't work).
DataTable dtItemPricingBreakDown =
SiteHelper.getItemPricingBreakDown(CustomerId,
PriceBookID,
deliveryZip,
dtItems,
db,
departmentId);
dtItemPricingBreakDown.AsEnumerable()
.GroupBy(i => new {
sku = i.Field<string>("sku"),
deptid = i.Field<int>("department_id")
})
.Select(group => new
{
sku = group.Key.sku,
deptid = group.Key.deptid,
cnt = group.Count()
});
Update
Better late than never, sorry for the delay in response. My actual issue appears to be for both the query syntax and the extension methods.
Something like this works according to msdn
(http://msdn.microsoft.com/en-us/library/bb386921(v=vs.110).aspx):
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
DataTable orders = ds.Tables["SalesOrderHeader"];
DataTable details = ds.Tables["SalesOrderDetail"];
var query =
from order in orders.AsEnumerable()
join detail in details.AsEnumerable() on order.Field<int>("SalesOrderID") equals detail.Field<int>("SalesOrderID")
where order.Field<bool>("OnlineOrderFlag") == true
&& order.Field<DateTime>("OrderDate").Month == 8
select new
{
SalesOrderID = order.Field<int>("SalesOrderID"),
SalesOrderDetailID = detail.Field<int>("SalesOrderDetailID"),
OrderDate = order.Field<DateTime>("OrderDate"),
ProductID = detail.Field<int>("ProductID")
};
DataTable orderTable = query.CopyToDataTable();
But when I try this...
var query = from exx in dtItemPricingBreakDown.AsEnumerable()
group exx by new { sku = exx.Field<string>("sku"), companyId = exx.Field<int>("department_id") } into grp
select new { sku = grp.Key.sku, DepartmentID = grp.Key.companyId, Cnt = grp.Count() };
DataTable dt3 = query.CopyToDataTable();
I get this exception: "No implicit reference conversion from anonymoustype1 to system.data.datarow". I've tried doing what they did with the dataset in the msdn example as well and I still get the error. Extension method wise I was trying something like this...and still got the same exception.
DataTable dt3 = dtItemPricingBreakDown.AsEnumerable().GroupBy(i => new
{
sku = i.Field<string>("sku"),
deptid = i.Field<int>("department_id")
}).Select(group => new
{
sku = group.Key.sku,
DepartmentID = group.Key.deptid,
cnt = group.Count()
}).Cast<DataRow>().CopyToDataTable();
Hi I am changing career to computer programming. I am still in college. I have to change the following LINQ query from method syntax to query syntax. What gets me is the 2 steps process of the method query. First it gets a teamId and then it returns a list based on the context and using the teamId. I am confused about how to translate this to query method. Most of the questions are about going from query syntax to method.
Can someone Help?
public IEnumerable<TemplateView> GetTemplates(Guid userId, int languageId)
{
using (DigigateEntities context = new Models.DigigateEntities())
{
var teamId = context
.TeamMembers
.Include("Team")
.FirstOrDefault(c => c.UserId == userId)
.Team.Id;
return context
.TeamTemplates.Include("Template")
.Where(c => c.TeamId == teamId)
.Select(c => c.Template)
.Where(c => c.StatusId == 1/*Active*/)
.Select(k => new TemplateView
{
TemplateName = k.Name,
Id = k.Id,
IsCustom = k.Custom,
TypeId = k.TypeId,
TypeName = k.TemplateType.Description,
FileName = k.FileName,
TemplateImage = "test.png",
LanguageId = k.LanguageId,
LanguageName = k.Language.Name,
CreateDate = k.CreateDate
}).ToList();
}
}
The first one is pretty straight forward. I delayed the execution of the query until the end. Since you may get a null reference exception in your example accessing .FirstOrDefault().Team.Id;
var teamId = (from c in context.TeamMembers.Include("Team")
where c.UserId == userId
select c.Team.Id).FirstOrDefault();
This one you just need to use an into in order to continue your query statement
return (from c in context.TeamTemplates.Include("Template")
where c.TeamId == teamId
select c.Template into k
where k.StatusId == 1
select new TemplateView
{
TemplateName = k.Name,
Id = k.Id,
IsCustom = k.Custom,
TypeId = k.TypeId,
TypeName = k.TemplateType.Description,
FileName = k.FileName,
TemplateImage = "test.png",
LanguageId = k.LanguageId,
LanguageName = k.Language.Name,
CreateDate = k.CreateDate
}).ToList();
public IEnumerable<TemplateView> GetTemplates(Guid userId, int languageId)
{
using (DigigateEntities context = new Models.DigigateEntities())
{
var teamId = (from tm in context.TeamMembers.Include("Team")
where tm.UserId==userId
select tm.Id).FirstOrDefault();
IEnumerable<TemplateView> result = from k in (from tmp in context.TeamTemplates.Include("Template")
select tmp.Template)
where k.StatusId==1
select new
{
TemplateName = k.Name,
Id = k.Id,
IsCustom = k.Custom,
TypeId = k.TypeId,
TypeName = k.TemplateType.Description,
FileName = k.FileName,
TemplateImage = "test.png",
LanguageId = k.LanguageId,
LanguageName = k.Language.Name,
CreateDate = k.CreateDate
};
return result;
}
I have a linq query which joins a couple of tables and returns the value into an object. The query was working fine, till i added a where clause to in. Aftre the where clause, my query returns null.
Here's the code:
List<Int32> resourceSupervisorIdList = new List<Int32>();
resourceSupervisorIdList.Add(searchCriteriaTimesheet.ResourceId);
foreach (resource res in allSubordinateResources)
{
if (!resourceSupervisorIdList.Contains(res.id_resource))
resourceSupervisorIdList.Add(res.id_resource);
}
using (tapEntities te = new tapEntities())
{
var timesheetAll = (from tsh in te.timesheet_header
join rs in te.resources on tsh.id_resource equals rs.id_resource
join tsd in te.timesheet_detail on tsh.id_timesheet equals tsd.id_timesheet
where (resourceSupervisorIdList.Contains(rs.id_resource_supervisor))
select new TimesheetHeaderDetailsItem()
{
OrganizationId = rs.id_organization,
ProjectId = tsd.id_project,
StartDate = tsh.dte_period_start,
EndDate = tsh.dte_period_end,
ApprovedDate = tsh.dte_approved,
RejectedDate = tsh.dte_rejected,
SubmittedDate = tsh.dte_submitted,
});
if (timesheetAll == null || timesheetAll.Count() == 0)
{
return result;
}
}
Now, after adding the where clause, the code runs into the if condition. There are matching records in the table, but still i'm not able to get any records.
rs.id_resource_supervisor
is of type int in the mysql db.
replacing the foreach loop
IList<EmployeeSearch> empItems = new List<EmployeeSearch>();
EmployeeSearch empItem = new EmployeeSearch();
foreach (var _emp in mediaResults.results)
{
empItem.Title = _emp.title;
empItem.Desc = _emp.description;
empItems.Add(empItem);
}
with the following linq expression and getting error:
empItems = from _emp in employeeResults.results
select new EmployeeSearch
{
Title = _emp.title,
Desc = _emp.description
};
Error:
Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IList'. An explicit conversion exists (are you
You need to convert it to a List:
(from _emp in employeeResults.results
select new EmployeeSearch
{
Title = _emp.title,
Desc = _emp.description
}).ToList();
Or...change your empItems definitions to use a var implicit typing:
var empItems = from _emp in employeeResults.results
select new EmployeeSearch
{
Title = _emp.title,
Desc = _emp.description
};
empItems will be an IEnumerable of EmployeeSearch objects.
Either add a call to the ToList extension method at the end of your query:
empItems =
(from _emp in employeeResults.results
select new EmployeeSearch
{
Title = _emp.title,
Desc = _emp.description
})
.ToList();
Or if you can possibly refactor your code to use an IEnumerable<T> instead, that could possibly be better:
IEnumerable<EmployeeSearch> empItems =
from _emp in employeeResults.results
select new EmployeeSearch
{
Title = _emp.title,
Desc = _emp.description
};
This should generally be used if you're just looping through the results and you don't actually need to add / remove elements from the result set or have per-index access to the results. Converting the query results to a list requires allocation of a single, contiguous array in memory, which is a fairly expensive operation.
How can I project the row number onto the linq query result set.
Instead of say:
field1, field2, field3
field1, field2, field3
I would like:
1, field1, field2, field3
2, field1, field2, field3
Here is my attempt at this:
public List<ScoreWithRank> GetHighScoresWithRank(string gameId, int count)
{
Guid guid = new Guid(gameId);
using (PPGEntities entities = new PPGEntities())
{
int i = 1;
var query = from s in entities.Scores
where s.Game.Id == guid
orderby s.PlayerScore descending
select new ScoreWithRank()
{
Rank=i++,
PlayerName = s.PlayerName,
PlayerScore = s.PlayerScore
};
return query.ToList<ScoreWithRank>();
}
}
Unfortunately, the "Rank=i++" line throws the following compile-time exception:
"An expression tree may not contain an assignment operator"
Well, the easiest way would be to do it at the client side rather than the database side, and use the overload of Select which provides an index as well:
public List<ScoreWithRank> GetHighScoresWithRank(string gameId, int count)
{
Guid guid = new Guid(gameId);
using (PPGEntities entities = new PPGEntities())
{
var query = from s in entities.Scores
where s.Game.Id == guid
orderby s.PlayerScore descending
select new
{
PlayerName = s.PlayerName,
PlayerScore = s.PlayerScore
};
return query.AsEnumerable() // Client-side from here on
.Select((player, index) => new ScoreWithRank()
{
PlayerName = player.PlayerName,
PlayerScore = player.PlayerScore,
Rank = index + 1;
})
.ToList();
}
}
Ok, that did the trick. Thanks.
Here is my final code...
Server:
public List<Score> GetHighScores(string gameId, int count)
{
Guid guid = new Guid(gameId);
using (PPGEntities entities = new PPGEntities())
{
var query = from s in entities.Scores
where s.Game.Id == guid
orderby s.PlayerScore descending
select s;
return query.ToList<Score>();
}
}
Client:
void hsc_LoadHighScoreCompleted(object sender, GetHighScoreCompletedEventArgs e)
{
ObservableCollection<Score> list = e.Result;
_listBox.ItemsSource = list.Select((player, index) => new ScoreWithRank()
{
PlayerName = player.PlayerName,
PlayerScore = player.PlayerScore,
Rank = index+=1
}).ToList();
}
You could also make just a slight adjustment to your original code to get it working. Word of caution, if you databind or access the object again, the Rank will increment each time. In those cases the top answer is better.
let Rank = i++
and
Rank.ToString()
Full code:
public List<ScoreWithRank> GetHighScoresWithRank(string gameId, int count)
{
Guid guid = new Guid(gameId);
using (PPGEntities entities = new PPGEntities())
{
int i = 1;
var query = from s in entities.Scores
let Rank = i++
where s.Game.Id == guid
orderby s.PlayerScore descending
select new ScoreWithRank()
{
Rank.ToString(),
PlayerName = s.PlayerName,
PlayerScore = s.PlayerScore
};
return query.ToList<ScoreWithRank>();
}
}
This solution worked for me.
http://www.dotnetfunda.com/articles/article1995-rownumber-simulation-in-linq.aspx
.Select((x, index) => new
{
SequentialNumber = index + 1
,FieldFoo = x.FieldFoo
}).ToList();
List<Emp> Lstemp = GetEmpList();
int Srno = 0;
var columns = from t in Lstemp
orderby t.Name
select new {
Row_number=++Srno,
EmpID = t.ID,
Name = t.Name,
City = t.City
};