Inner join on the parent document from within a child - join

I have a document that looks like this:
{
"id": "some guid",
"name": "Bob",
"following": [
{
"id": "some_guid",
"priority": true
}
]
}
The idea is that a user can follow other users.
What I would like to do is, for a given user get the IDs and names of all users that they are following. The name is not stored with in the "following" collection.
If I were using SQL, I'd be doing something like this:
SELECT u.following_id, u.priority, j.name FROM users INNER JOIN j on u.following_id = j.id.
What is the equivalent in DocumentDb SQL?

The equivalent in DocumentDB is to do two round trips. First fetch the user document containing the array of who that user is following. Then build up a big OR clause and use that to fetch the documents of who they are following.
Alternatively, you may want to store the relationship in the other direction. So instead of storing who one user follows in that user's document, store the followedBy list in each of the followers. You can then do an ARRAY_CONTAINS query in one round trip.
You also might want to look at Azure's stream analytics product because it has graph querying capabilities.

Related

How to do grouping in elasticsearch with searchkick rails

I have articles data indexed to elastic as follows.
{
"id": 1011,
"title": "abcd",
"author": "author1"
"status": "published"
}
Now I wanted to get all the article id grouped by status.
Result should someway look like this
{
"published": [1011, 1012, ....],
"draft": [2011],
"deleted": [3011]
}
NB: I tried normal aggs (Article.search('*',aggs: [:status], load: false).aggs) , it just giving me the count of each items in, I want ids in each item instead
#Crazy Cat
You can transform you query in this way:
sort(Inc/Dec order) your response from ES over field "status".
Only Ask ES query to return only ID Field and status.
Now the usage of sorting would be it would sort your response to like this: [1st N results of "deleted" status, then N+1 to M results to "draft" and then M+1 to K results to "published"].
Now the advantages of this technique:
You will get flagged ids field of every document over which you can apply operations in you application.
Your query would be light weight as compared to Aggs query.
This way you would also get the metdata of every document ike docId of that document.
Now the Disadvantages:
You would always have to give a high upper bound of your page size, but You can also play around with count coming in the metadata.
Might take a bit more of network size as it returns redundant status in every document.
I Hope this redesign of your query might be helpful to you.

Rails - Create order and order-rows with REST api

I just have a question regarding how to implement some logic.
Im building a API that allows the client to create orders.
This is solved by a OrderController#create so no problem!
Now, the issue is that an order can have many order-rows, all the relations are set correct but where should i create the order-rows in for the order?
Should the OrderController handle this or should i have a new controller that creates the order-rows for the particular order?
The clients post is sending the following json-data:
{
"status": "paid",
"total_sum": 20,
"payment": "card",
"order_rows": [
{
"id": 12,
},
{
"id":13
}
]
}
I ran into something similar with a project I'm working on now. The best (and long term simplest) solution was definitely to make a whole new model/controller.
*Order
status (should be an int or enum probably)
total (should loop through all order rows and total)
payment (should be an int or enum probably)
has_many order_rows
**OrderRow
belongs_to Order
item_sku
item_name
item_descr
item_cost
etc. etc.
This allows you to easily search for not just items, but orders that include items by name or sku, orders that include items by description.
Your totals are dynamic.
You can retrieve total order numbers or movement numbers on a per item basis.
It is so much easier to create and update orders.
The benefits go on.
It can easily be scoped;
scope :this_orders_rows, -> (order_id) {where(order_id: order_id)}
And it saves you from having to parse through hashes and arrays everytime.
To get technical about it, your order_controller should control ONLY your orders. If you start adding in a heap of other code to read through the arrays its going to get VERY cluttered. It's always better to move that to some other area.

How to filter for a object wiith a "value" and "name" in QBO api?

It seems like its the api won't permit a query filter of the form:
select * from purchaseorder where APAccountRef.value='33'
In the case of purchase orders it seems to mean that I need to bring down every purchase order to my server and scan for the account I need which is highly suboptimal. Is there some other syntax for querying against the many attributes which have been encoded like
"APAccountRef": {
"value": "33",
"name": "Accounts Payable (A/P)"
}
with just a name and value attribute?
If you refer to the documentation:
https://developer.intuit.com/docs/api/accounting/purchaseorder
It gives you a list of all fields, and a list of fields that are filterable. Your query is using a field that does not exist as part of Purchase Orders:
AccountRef.value='39'
The correct field is:
APAccountRef:
required
ReferenceType, filterable
Specifies to which AP account the bill is credited.
So your query should be:
SELECT * FROM purchaseorder WHERE APAccountRef = '39'
Try this in python-
"select * from purchaseorder where APAccountRef in ('33')"

Grails 3 - return list in query result from HQL query

I have a domain object:
class Business {
String name
List subUnits
static hasMany = [
subUnits : SubUnit,
]
}
I want to get name and subUnits using HQL, but I get an error
Exception: org.springframework.orm.hibernate4.HibernateQueryException: not an entity
when using:
List businesses = Business.executeQuery("select business.name, business.subUnits from Business as business")
Is there a way I can get subUnits returned in the result query result as a List using HQL? When I use a left join, the query result is a flattened List that duplicates name. The actual query is more complicated - this is a simplified version, so I can't just use Business.list().
I thought I should add it as an answer, since I been doing this sort of thing for a while and a lot of knowledge that I can share with others:
As per suggestion from Yariash above:
This is forward walking through a domain object vs grabbing info as a flat list (map). There is expense involved when having an entire object then asking it to loop through and return many relations vs having it all in one contained list
#anonymous1 that sounds correct with left join - you can take a look at 'group by name' added to end of your query. Alternatively when you have all the results you can use businesses.groupBy{it.name} (this is a cool groovy feature} take a look at the output of the groupBy to understand what it has done to the
But If you are attempting to grab the entire object and map it back then actually the cost is still very hefty and is probably as costly as the suggestion by Yariash and possibly worse.
List businesses = Business.executeQuery("select new map(business.name as name, su.field1 as field1, su.field2 as field2) from Business b left join b.subUnits su ")
The above is really what you should be trying to do, left joining then grabbing each of the inner elements of the hasMany as part of your over all map you are returning within that list.
then when you have your results
def groupedBusinesses=businesses.groupBy{it.name} where name was the main object from the main class that has the hasMany relation.
If you then look at you will see each name has its own list
groupedBusinesses: [name1: [ [field1,field2,field3], [field1,field2,field3] ]
you can now do
groupedBusinesses.get(name) to get entire list for that hasMany relation.
Enable SQL logging for above hql query then compare it to
List businesses = Business.executeQuery("select new map(b.name as name, su as subUnits) from Business b left join b.subUnits su ")
What you will see is that the 2nd query will generate huge SQL queries to get the data since it attempts to map entire entry per row.
I have tested this theory and it always tends to be around an entire page full of query if not maybe multiple pages of SQL query created from within HQL compared to a few lines of query created by first example.

filtering relationships in neo4js

I am using neo4js to store users as nodes with property as user_id. There is a friend relation from user1 to user 2.
I am trying to find the incomming friend connections on node user2(user_id =2) which are comming from node with user_id=1.
I am using the neography library for the same.
https://github.com/maxdemarzi/neography/
u2 = Neography::Node.(id)
u2.outgoing(:friends).filter("..........")
I am not sure what exact filter should be given so that I can filter out the relationships comming from node(s) with user_id=1.
Regards,
Pankaj
You can use a traversal in neo4js to find those relationships.
This is untested code, but you want to do something like this:
var promise = somenode.traverse({
"prune_evaluator": {
"language": "javascript",
"body": "position.endNode().getId()!=2;" // Note that this is a string
}},
neo4j.traverse.RETURN_RELATIONSHIPS);
promise.then(function(relationships) {
console.log(relationships);
});
The first argument to the traverse method is a traversal object, for full docs on what you can put there, see http://docs.neo4j.org/chunked/snapshot/rest-api-traverse.html

Resources