Graph DB: Sort product based on likes - graph-databases

I have a product vertex which has incomming like edge.
User ------- likes ----------->products
In my search result I want to sort the products based on likes. How this can be done ?

Just use groupCount:
gremlin> g = new TinkerGraph()
==>tinkergraph[vertices:0 edges:0]
gremlin> user1 = g.addVertex('u1')
==>v[u1]
gremlin> user2 = g.addVertex('u2')
==>v[u2]
gremlin> product1 = g.addVertex('p1')
==>v[p1]
gremlin> product2 = g.addVertex('p2')
==>v[p2]
gremlin> product3 = g.addVertex('p3')
==>v[p3]
gremlin> user1.addEdge('like',product1)
==>e[0][u1-like->p1]
gremlin> user1.addEdge('like',product2)
==>e[1][u1-like->p2]
gremlin> user2.addEdge('like',product2)
==>e[2][u2-like->p2]
gremlin> user2.addEdge('like',product3)
==>e[3][u2-like->p3]
gremlin> g.v('u1','u2').out('like').groupCount().sort{-it.value}
Cannot invoke method negative() on null object
Display stack trace? [yN] n
gremlin> g.v('u1','u2').out('like').groupCount().cap.next().sort{-it.value}
==>v[p2]=2
==>v[p1]=1
==>v[p3]=1

Related

Create a list of custom type in F# and create two sequences of that list

I have created my own type in F# called Accounts and I have then created objects for each account.
type Account() =
let AccountNumber = ""
let mutable Balance:float = 0.0
Every account has two fields, AccountNumber (string) and Balance (float).
I have then created an object for every account that holds the AccountName and the Balance.
let acc1 = new Account()
acc1.Insert("John",10.0)
let acc2 = new Account()
acc2.Insert("Mike",50.0)
How do I create a list that holds each account (object)? I have tried the following:
let AccountList : Account list = [acc1; acc2 ; acc3; acc4 ; acc5; acc6]
let AccountList : Account obj list = [acc1; acc2 ; acc3; acc4 ; acc5; acc6]
I cannot solve the problem using the above method because I have to create two sequences from the list:
Sequence 1: All accounts with a balance greater or equal to zero and less than 50
Sequence 2: All accounts with a balance above 50
How do I create a list of my custom type in F# and how do I create two sequences of that list?
It is not clear what exactly are you struggling with. However, the following simple example should illustrate most of the key ideas that you probably need to use. First, here is a small version of your Account class (note that I would normally use an immutable record, but I kept it the way you did it):
type Account(balance:float) =
let mutable balance = balance
member x.Balance = balance
member x.Add(difference) =
balance <- balance + difference
I do not see what issue you have with creating the list. The following works just fine:
let acc1 = Account(100.0)
let acc2 = Account(10.0)
let accountList = [acc1; acc2]
Now, to answer the question about finding accounts with balance over 50, you can use the List.filter function to create a new filtered list:
let above50 =
accountList |> List.filter (fun acc ->
acc.Balance > 50.0)
EDIT If you wanted to use a record instead, then you would define the type as:
type Account = { Balance : float }
And create a value using:
let acc1 = { Balance = 100.0 }
So I created this answer for the other one but I was waiting on the comment to see if I would answer. And the homework like aspect of this :)
So if you have criteria that bucket an account and want to do that in a single pass, you might want to look at groupBy. Here I use a boolean because there are only 2 possibilities but numbers or a discriminated union are good candidates.
open System
type Account(accountNumber:string, startingBalance:Int64) =
let mutable balance = startingBalance
member _.Balance = balance
member _.Deposit amount = balance <- balance + amount
member _.Withdraw amount = balance <- balance - amount
override _.ToString() = accountNumber
let allAccounts = [Account("ABC1", 10L); Account("ABC2", 50L)]
let grouped = allAccounts |> List.groupBy (fun a -> a.Balance >= 50L) |> Map.ofList
let under50 = grouped |> Map.tryFind false |> Option.defaultValue []
let overIncl50 = grouped |> Map.tryFind true |> Option.defaultValue []
printfn "Under: %A" under50
printfn "Over: %A" overIncl50

How to "join" vertices and the count of their edges as a 'property' of those vertices in JanusGraph or Gremlin?

I need to return the 'posts' vertices, but those posts have some 'like' edges, how can I return the count of 'likes' edges for that posts as a property of that edge, like this:
{ title: 'lorem ipsum.....',
content: 'yadayadayada',
likes: 6 <----
}
Using TinkerPop's modern toy graph as an example, you could do something like this:
gremlin> g.V().as('a').
......1> map(outE('created').count()).as('count').
......2> select('a','count').by(valueMap()).by()
==>[a:[name:[marko],age:[29]],count:1]
==>[a:[name:[vadas],age:[27]],count:0]
==>[a:[name:[lop],lang:[java]],count:0]
==>[a:[name:[josh],age:[32]],count:2]
==>[a:[name:[ripple],lang:[java]],count:0]
==>[a:[name:[peter],age:[35]],count:1]
It returns the properties of the vertices in "a" and the count of "created" edges. You might also choose to use project():
gremlin> g.V().
......1> project('a','knows','created').
......2> by(valueMap()).
......3> by(outE('knows').count()).
......4> by(outE('created').count())
==>[a:[name:[marko],age:[29]],knows:2,created:1]
==>[a:[name:[vadas],age:[27]],knows:0,created:0]
==>[a:[name:[lop],lang:[java]],knows:0,created:0]
==>[a:[name:[josh],age:[32]],knows:0,created:2]
==>[a:[name:[ripple],lang:[java]],knows:0,created:0]
==>[a:[name:[peter],age:[35]],knows:0,created:1]

Search data in JSON array And Put in in array list in grails

I have a list like [gender, axonVoucherCode]
Also I have a Json Array [[gender:Gender?], [concussionHistory:History of previous concussion?], [previousConcussion:Number of previous concussions?], [historyMigraineChronic:History of migraine or chronic headaches?], [edTreatment:ED treatment ?], [axonVoucherCode:Axon Voucher Code ?]]
I want to make a list with corresponding value of 1st list like [Gender?,Axon Voucher Code ?] .I use JsonSlurper for parsing Json .
def fetchQuestion(def list){
def webRootDir = SCH.servletContext.getRealPath("/")
def f = new File(webRootDir + "/jsons/" + "QuestionPart1")
def questionList = new JsonSlurper().parseText(f.text)
def newlists=[]
println questionList.QuestionPart1
questionList.QuestionPart1.each{
println(it)
}
println(newlists);
return newlists
}
//I want to put matching value to newlists
Here is my JSON file format .
{"QuestionPart1":[
{"gender":"Gender?"},
{"concussionHistory":"History of previous concussion?"},
{"previousConcussion":"Number of previous concussions?"},
{"historyMigraineChronic":"History of migraine or chronic headaches?"},
{"edvisitTime":"Date and time of ED visit?"},
{"injuryTime":"Date and time of Injury?"},
{"mechanismInjury":"Mechanism of Injury?"},
{"sportsType":"Choose Sport?"},
{"signAndSymptom":"Select the signs and symptoms the subject experienced following injury?"},
{"durationLossConsciousness":"Duration of loss of Conciousness ? "},
{"durationBeforeAmnesia":"Duration of Amnesia for events BEFORE injury ?"},
{"durationAfterAmnesia":"Duration of Amnesia for events AFTER injury ?"},
{"ctObtainedED":"Head CT obtained in ED ?"},
{"edTreatment":"ED treatment ?"},
{"axonVoucherCode":"Axon Voucher Code ?"}
]}
Please help me to solve this problem .Thanks
Assuming I understand your question, this should work:
def fetchQuestion(String ...keys){
def webRootDir = SCH.servletContext.getRealPath("/")
def f = new File(webRootDir + "/jsons/" + "QuestionPart1")
def questionList = new JsonSlurper().parseText(f.text)
def newlists=[]
println questionList.QuestionPart1
questionList.QuestionPart1.findResults { it.find { k, v -> k in keys }?.value }
}
def listOfValues = fetchQuestion('edvisitTime', 'axonVoucherCode')
Here, listOfValues will equal ['Date and time of ED visit?', 'Axon Voucher Code ?']

Realm: Querying and Indexing with One-to-Many relationship

Lets consider the default Realm example of Person and Dog.
Person with name 'A' has 3 Dogs with respective names - 'X', 'Y', 'Z'
Person with name 'B' has 2 Dogs with respective names - 'X', 'Z'
So the code will be
[realm beginWriteTransaction];
Person *personA = [Person createInRealm:realm withObject:#{#"name": #"A"}];
Person *personB = [Person createInRealm:realm withObject:#{#"name": #"B"}];
[Dog createInRealm:realm withObject:#{#"name": #"X", #"owners": #[personA, personB]}];
[Dog createInRealm:realm withObject:#{#"name": #"Y", #"owners": #[personA]}];
[Dog createInRealm:realm withObject:#{#"name": #"Z", #"owners": #[personA, personB]}];
[realm commitWriteTransaction];
Now, in order to get all the dogs based on owners we write
RLMArray *dogs = [Dog objectsWhere:#"ANY owners = %#", personA];
or
RLMArray *dogs = [Dog objectsWhere:#"ANY owners = %#", personB];
How should we set index in this case to improve performance?
How can we inverse link so that we can do
RLMArray *persons = [Person objectsWhere:#"ANY dogs = %#", dogX];
That's not supported yet.
For now you can change the direction of your relationship and have a property of type RLMArray<Dog> on Person, if you need to traverse it more often in that direction. Alternatively you can maintain two relationships in both direction, you would need to sync them yourself.
We track adding support for that by issue #1324.

How to getting paths that are self-loops using GremlinPipeline?

I'm working with a network that allows self-loops (i.e., some edges have the same vertex as both head and tail). Suppose, the graph g has 3 vertices (adam, bill, and cid), and 3 edges of type reports ([adam-reports->bill], [bill-reports->cid], and [adam-reports->adam]), the last being the only reflexive edge in this example.
gremlin> g = new TinkerGraph();
gremlin> adam = g.addVertex('adam');
gremlin> bill = g.addVertex('bill');
gremlin> cid = g.addVertex('cid');
gremlin> g.addEdge(adam, bill, 'reports');
gremlin> g.addEdge(bill, cid, 'reports');
gremlin> g.addEdge(adam, adam, 'reports');
In gremlin, the self-loop(s) can be easily retrieved, thus:
gremlin> g.V.sideEffect{v=it}.outE('reports').inV.filter{it==v}.path
gremlin> [v[adam], e[2][adam-reports->adam], v[adam]]
However, I'm trying to do the same using GremlinPipeline in Java without success. How can I build a valid GremlinePipeline to do the above?
GremlinPipeline pp = new GremlinPipeline();
// Add various pies to pp to get a valid pipeline
pp.setStarts(g.getVertices());
If you only want to find self-loop edges, do this:
g.E.filter{it.inV == it.outV}
Given you sample TinkerGraph above, the output is:
gremlin> g.E.filter{it.inV == it.outV}
==>e[2][adam-reports->adam]

Resources