Social‎ > ‎Technotes‎ > ‎

GAS Doclist find and getFiles for filtering

posted Oct 18, 2012, 6:35 PM by Faustino Rodriguez
When writing an App using Google Apps Script (that's GAS;) I had to provide some documents list within a folder with filtering functionality. So when the user enter a search string the App would list all documents within the App folder that matched that criteria, being within title or the actual content.

What I have learnt so far?

1. Google doesn't search within the actual documents but in their indexes, what makes a lot of sense Google-wise, however you have to be prepare for some delay for recent documents to appear on that search (minutes, hours, maybe more?). In the mean time you better remember what was about your latest documents.

2. Google will search within the revisions history of your documents, so it will show documents that match your search even if they are not currently containing that string criteria but they had in the past, what is good, very good.

3. My first "naive" approach to search was using always the function find like this line of code below
qDocsFolder.find(e.parameter.filterDocs)
However, I ended finding out that searching for an empty string will take a lot of time (many seconds I mean)
I had to change the approach using getFiles function for empty string instead, like below few more code lines
var qDocsFolder = DocsList.getFolder(e.parameter.qDocsFolderPath_);
var allDocs = (e.parameter.filterDocs) ? qDocsFolder.find(e.parameter.filterDocs) : qDocsFolder.getFiles();

4. When doing as above I found out (at least in my case) that find function will return documents sorted by "last modified date, reverse" while getFiles function would sorted by "document name, normal". Just to get more consistency and having all sorted by "last modified date, reverse", as it was the requirement to show the more recent changes first, I introduced an intermediate array to sort as below
var qDocsFolder = DocsList.getFolder(e.parameter.qDocsFolderPath_);
var allDocs = (e.parameter.filterDocs) ? qDocsFolder.find(e.parameter.filterDocs) : qDocsFolder.getFiles();
var allDocs3Array = [];
for (var i in allDocs) allDocs3Array.push([allDocs[i].getName(), allDocs[i].getId(), allDocs[i].getLastUpdated()]);
allDocs3Array.sort(function(a,b){return b[2] - a[2];});
In this case we get the documents list sorted by getLastUpdated reverse and the first two elements of this array are ready to be added as items in a list box.

ps. I would update this post if anything else important comes to my attention on this subject.
Comments