Search code examples
sqlaggregateaverageorientdb

OrientDB average over collection


Im trying orientdb with some simple apps.

In this app I have People (persona) and places to eat (sitio), people go to those places (I store how many times they do) and score them.

Using this query:

SELECT *, 
inE('puntua').comida as comida, 
inE('puntua').servicio as servicio, 
inE('puntua').extras as extras
from Sitio

I managed to get all places with its scores, but the scores in an array and I cannot apply Avg() function.

Data Returned By Query

tldr;

Am I misunderstanding this new Graph modeling technique? or there is a better aproach to get those averages?

GraphDB


Solution

  • EDITED

    create class Puntua extends E
    
    create class Sitio extends V
    
    create class Persona extends V
    
    create vertex Persona set name = 'person' # returns #17:0
    create vertex Sitio set place = 'mcdonals' # returns #16:0
    create vertex Sitio set place = 'burgerking'
    create vertex Sitio set place = 'glicinia' # returns #16:2
    
    create edge Puntua from 17:0 to 16:0 set comida = 8, servicio = 9, = extras = 7
    create edge Puntua from 17:0 to 16:0 set comida = 8, servicio = 7, = extras = 9
    create edge Puntua from 17:0 to 16:2 set comida = 8, servicio = 7, = extras = 9
    

    If the above is your situation, I believe the query you're looking for is something like:

    SELECT *, myAvg(comida), myAvg(servicio), myAvg(extras) 
    FROM (
       SELECT place, 
          inE('Puntua').comida as comida, 
          inE('Puntua').servicio as servicio, 
          inE('Puntua').extras as extras
       FROM Sitio
    )
    

    where myAvg is a javascript function:

    var graph = orient.getGraph();
    var res = graph.command( "sql", "select avg(list) from (select " + list + " as list)");
    if(res.length > 0){
        return res[0].getRecord().field('avg');
    } else{
        return null;
    }
    

    like here. (note the list argument)

    The output is this.