RavenDB HTTP API via Google Apps Script (JavaScript), Spreadsheets and Documents

Here's a very quick code snippet I'll be documenting more later...

  1. Create a new Spreadsheet in Google Docs / Google Drive
  2. Click Tools > Script Editor
  3. Paste
  4. Enjoy

Also see:

getRaven()
- Utilizes RavenDB's HTTP API, authenticating via Basic Authentication. [1]
- Queries an index and returns the first 1024 items. [2]
- Gets an aggregate of the frequency of occurance of each field.
- Prompts the user to modify the list of fields that will be imported into the Spreadsheet.
- Imports this content into the Google Spreadsheet.

[1]: I must double check to see if you need to be running RavenDB on IIS to use Basic Autentication. I am at present.
[2]: Put this in a while loop if you need more documents.

toDocuments()
- Loops through columns A:B and creates new Google Documents, using A as the Document name and B as the Document content.

onOpen()
- Adds menu items to execute getIndex() and toDocuments() above.

function getRavenIndex() 
{
  var db = "https://example.com/databases/db1";
  var user = "Username";
  var pass = "Password";

  var param1 = { headers: {"Authorization": "Basic " + Utilities.base64Encode(user+":"+pass)} };
  var query1 = db + "/indexes/Raven/DocumentsByEntityName?query=Tag:Posts&pageSize=1024&start=";
  var result1 = UrlFetchApp.fetch(query1, param1).getContentText();
  var object1 = Utilities.jsonParse(result1);

  var fields = {};
  for(var i = 0; i < object1.Results.length; i++)
  {
    for(var key in object1.Results[i])
    {
      fields[key] = (fields[key] || 0) + 1;
    }
  }
  //Logger.log(fields);

  var key1 = [];
  for(var key in fields){ key1.push(key); };
  key1 = (Browser.inputBox(key1.join(',')) || key1.join(',')).split(',');

  var rows = [];
  for(var i = 0; i < object1.Results.length; i++)
  {
    var row = [];
    row.push(object1.Results[i]['@metadata']['@id']); // always includes @id
    for(var j = 0; j < key1.length; j++)
    {
      row.push(object1.Results[i][key1[j]]);
    }
    rows.push(row);
  }
  key1 = ['@id'].concat(key1); // always includes @id
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().clear().appendRow(key1);
  sheet1.getRange(2, 1, rows.length, rows[0].length).setValues(rows);      
}
function toDocuments()
{
  var val1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A:B").getValues();
  for(var i = 0; i < val1.length; i++)
  {
    var doc1 = DocumentApp.create(val1[i][0]).setText(val1[i][1].replace(new RegExp( "\\n", "g" ), "")).saveAndClose();
  }
}
function onOpen()
{
  SpreadsheetApp.getActiveSpreadsheet().addMenu("MyTools", [{name:"getRavenIndex", functionName:"getRavenIndex"},{name:"toDocuments", functionName:"toDocuments"}]);
}