How to get RqlCursor (response after running query) into java Map? - rethinkdb

I am using Rethinkdb Java driver, How can I convert RqlCursor to Map in java?
RqlCursor cur = r.db("test").table("x").insert({"a":"b"})
How to convert this cur to Hashmap or Map?

You can iterate the cursor for query results and there is a getMap method in the result object
That insert query returns certain attributes, you can retrieve them for example like this:
for(RqlObject o : cur) {
o.getAs("inserted").toString();
o.getAs("replaced").toString();
o.getAs("unchanged").toString();
o.getAs("errors").toString();
}

Related

How to set Filter Values in LinQ with SQL Query Text?

I am using LINQ for my database application.
So I can write things like:
using (ShuttleDataContext dc = Config.GetNewShuttleDBConnection())
{
List<RefState> states = (from a in dc.RefStates select a).ToList();
return states;
}
Know I have to handle the requierement, that I have to filter from this database by SQL strings, e.g. a filter string: "ID like '7%'" or "Name = 'Red'".
Of course normaly I would write something like .Where(a => a.Name == "Red"), but it's nearly impossible to map every filterexpression to a where clause... So is there a method to have native T-SQL in an Linq-List?
As far as I know you can't just provide the filter condition, but you can use ExecuteQuery to execute an arbitrary SQL statement and map that to your LINQ types:
List<RefState> states = dc.ExecuteQuery<RefState>(
"SELECT * FROM RefStates WHERE ID LIKE '7%'").ToList();

IQueryable type to an Array

I have a dynamic Linq query like this. I need to convert the result set into an array. But I am not able to convert the IQueryable type to an Array. Any suggestion?
my code:-
var query = Data.AsEnumerable()
.AsQueryable()
.Select("new(it[\"Country\"] as Country)", "it")
.Take(10);
foreach (string str in query) // **getting error Unable to cast object of type 'DynamicClass1' to type 'System.String**
{
}
I fixed it using like this :- foreach(var str in query) .
But I have another issue now. I have added where condition to the query. Now i am getting error "No property or field 'Country' exists in type 'DataRow'".
following is my query
var query= Data.AsEnumerable().AsQueryable().Where("Country = #0", "London").Select("new (Country as Country)");
When you use Dynamic LINQ all extensions returns collection with dynamic elements, so you need change your code for example like this
foreach (dynamic str in query)
{
....
}
also for your case str is object with field Country
UPDATE
for question from comment
if Data is DataTable when you call AsEnumerable or AsQueryable you work with collection of DataRow, so when you want filter it by column value you need use syntax for DataRow like this
Data.AsQueryable().Where("it[\"Country\"] = #0", "London")
or you can do select first like that
var query= Data.AsQueryable()
.Select("new (it[\"Country\"] as Country)")
.Where("Country = #0", "London")
UPDATE2
until you don't specify type for field it can be Object so you need change Select clause like this
....
.Select("new(Convert.ToString(it[\"Country\"]) as Country)")
....
in this case when you call Where after Select field Country will is String, so String have Contains method

Linq query returns null. Can't figure out why

My result returns null.
IEnumerable<DataRow> result = ( from r in db.vedhaeftedeFilers.AsEnumerable() where r.beskedId == id select new { r.filnavn, r.filtype, r.data })as IEnumerable<DataRow>;
there are data in the database, and the id are correct. I am guessing that it has
something to do with my use of IEnumerable, but cant figure out what the problem is.
The as operator will return null if the object you are passing is not actually an IEnumerable<DataRow>, which it obviously is not because you are projecting into an anonymous type with select new { ... }.
As an aside, the AsEnumerable() call will ruin your performance by making your database table behave like a dumb array.
What exactly are you trying to do here?
select new { r.filnavn, r.filtype, r.data }
That creates an anonymous type with read only properties filnavn, filtype and data. Thus the type of the LINQ comprehension expression (from ... select) is IEnumerable<anonymous>.
This type does not implement IEnumerable<DataRow>, so as Jon notes, it will return null.
When you do this:
select new { r.filnavn, r.filtype, r.data }
...you are returning a collection of an anonymous type. This is a problem because you're trying to cast this collection to IEnumerable<DataRow>. Since you're using as to cast, it's "dying silently" and returning null since casting with the as keyword doesn't throw an InvalidCastException if the cast fails (as opposed to casting with parethesis like MyClass x = (MyClass)MyObj).
Try this instead:
var result = ( from r in db.vedhaeftedeFilers.AsEnumerable() where r.beskedId == id select new { r.filnavn, r.filtype, r.data });
Notice I used var and didn't attempt to cast the result to a type.

Longish LINQ query breakes SQLite-parser - simplify?

I'm programming a search for a SQLite-database using C# and LINQ.
The idea of the search is, that you can provide one or more keywords, any of which must be contained in any of several column-entries for that row to be added to the results.
The implementation consists of several linq-queries which are all put together by union. More keywords and columns that have to be considered result in a more complicated query that way. This can lead to SQL-code, which is to long for the SQLite-parser.
Here is some sample code to illustrate:
IQueryable<Reference> query = null;
if (searchAuthor)
foreach (string w in words)
{
string word = w;
var result = from r in _dbConnection.GetTable<Reference>()
where r.ReferenceAuthor.Any(a => a.Person.LastName.Contains(word) || a.Person.FirstName.Contains(word))
orderby r.Title
select r;
query = query == null ? result : query.Union(result);
}
if (searchTitle)
foreach (string word in words)
{
var result = from r in _dbConnection.GetTable<Reference>()
where r.Title.Contains(word)
orderby r.Title
select r;
query = query == null ? result : query.Union(result);
}
//...
Is there a way to structure the query in a way that results in more compact SQL?
I tried to force the creation of smaller SQL-statments by calling GetEnumerator() on the query after every loop. But apparently Union() doesn't operate on data, but on the underlying LINQ/SQL statement, so I was generating to long statements regardless.
The only solution I can think of right now, is to really gather the data after every "sub-query" and doing a union on the actual data and not in the statement. Any ideas?
For something like that, you might want to use a PredicateBuilder, as shown in the chosen answer to this question.

LINQ Aggregate vs. nested foreach

I am trying to achieve:
foreach (ScheduleItem s in ScheduleItems)
{
foreach (IScheduleModule m in s.ScheduleModules)
{
yield return m;
}
}
using LINQ aggregate and I do not understand why
return ScheduleItems.Aggregate(new Collection<IScheduleModule>(), (x, o) => x.Union(o.ScheduleModules) as Collection<IScheduleModule>);
returns null.
I have no issue using the nested foreach but my instinct was to use aggregate and I don't understand why it doesn't produce the same result.
Are there other approaches? What is best in terms of readability and performance?
You should be using SelectMany for this:
ScheduleItems.SelectMany(s => s.ScheduleModules)
That exactly matches your initial nested foreach loop. It's also equivalent to this query expression:
from s in ScheduleItems
from m in s.ScheduleModules
select m
(although that will use a slightly different form of SelectMany).
As for why Aggregate isn't working: you're calling Union which returns an IEnumerable<T>, but then using as to try to convert it to Collection<T>. The result of Union won't be a Collection<T>, hence the result of the as operator is null.
Have you tried using SelectMany? Based on your question, that sounds like what you are looking for.
var results = ScheduleItems.SelectMany(si => si.ScheduleModules);

Resources