How to write a select query or server-side function that will generate a neat time-flow graph from many data points?

跟風遠走 提交于 2019-12-05 05:32:08

Holy cow.

After wrestling with this for over a week I think I FINALLY have a working function. This isn't optimized for performance (oh the loops!), but gets the job done for the time being while I can work on performance. The resulting OrientDB server-side function (written in javascript):

The function:

// Clear previous runs
db.command("truncate class tmp_Then");
db.command("truncate class tmp_Events");

// Get all distinct events
var distinctEvents = db.query("select from Events group by event");

// Send 404 if null, otherwise proceed
if (distinctEvents == null) {
  response.send(404, "Events not found", "text/plain", "Error: events not found" );
} else {
  var edges = [];

  // Loop through all distinct events
  distinctEvents.forEach(function(distinctEvent) {
    var newEvent = [];
    var rid = distinctEvent.field("@rid");
    var eventType = distinctEvent.field("event");

    // The main query that finds all *direct* descendents of the distinct event
    var result = db.query("select from (traverse * from (select from Events where event = ?) where $depth <= 2) where @class = 'Events' and $depth > 1 and @rid in (select from Events group by event)", [eventType]);

    // Save the distinct event in a temp table to create temp edges
    db.command("create vertex tmp_Events set rid = ?, event = ?", [rid, event]);
      edges.push(result);
    });

  // The edges array defines which edges should exist for a given event
  edges.forEach(function(edge, index) {
    edge.forEach(function(e) {
      // Create the temp edge that corresponds to its distinct event
      db.command("create edge tmp_Then from (select from tmp_Events where rid = " + distinctEvents[index].field("@rid") + ") to (select from tmp_Events where rid = " + e.field("@rid") + ")");
    });
  });

  var result = db.query("select from tmp_Events");
  return result;
}

Takeaways:

  • Temp tables appeared to be necessary. I tried to do this without temp tables (classes), but I'm not sure it could be done. I needed to mock edges that didn't exist in the raw data.
  • Traverse was very helpful in writing the main query. Traversing through an event to find its direct, unique descendents was fairly simple.
  • Having the ability to write stored procs in Javascript is freaking awesome. This would have been a nightmare in SQL.
  • omfg loops. I plan to optimize this and continue to make it better so hopefully other people can find some use for it.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!