0

In my Apple Notes automation on macOS Big Sur, I’d like to load any 5 notes whose name contains a substring. For example, if I know that I actually have 5 notes that match the query, I can write something like this:

tell application "Notes"
  set matches to id of (notes 1 thru 5 in default account whose name contains "a")
end tell

This runs relatively fast (< 1 second on my account with thousands of notes), because it terminates as soon as it finds those 5 matches and doesn’t look any further. For comparison, a query without such "1 thru 5" clause (or a count query) times out before it even returns any results, which is understandable. However, my problem is that if there aren’t enough (i.e., fewer than 5) matches, the query will error without returning any results:

Notes got an error: Can’t get notes 1 thru 5 of default account whose name contains "a". Invalid index.

Thus, my question is whether there’s a way for me to get "at most 5 results" in a single query?

0

1 Answer 1

1

Thus, my question is whether there’s a way for me to get "at most 5 results" in a single query?

No, it cannot be done in a single query.

If you want to loop through a given count downwards then the following example AppleScript code is how I'd do it:

set maxNumber to 5
set searchString to "a"

set matches to missing value
repeat with i from maxNumber to 1 by -1
    if matches is equal to missing value then
        try
            tell application "Notes"
                set matches to id of ¬
                    (notes 1 thru i in default account ¬
                        whose name contains searchString)
            end tell
        end try
        if matches is not equal to missing value then exit repeat
    end if
end repeat

return matches
3
  • This is not a single query (one gets the count and another fetches the items) and I specifically said that getting the count will timeout.
    – temochka
    Commented Jan 15, 2021 at 23:37
  • @temochka, I've update my original answer to first explicitly answer the question you asked which unfortunately is no, and to provide a smart way of coding a loop if you want to go that route. If you don't want to go that way just let me know and I'll delete the answer. Commented Jan 16, 2021 at 3:18
  • I also did more research and I agree with your conclusion that this cannot be done: the underlying Apple Event is limited to fetching a strictly defined range of entries. With that in mind, the solution in your answer seems to be the best option I have for my purposes so I’m going to accept it. Thanks!
    – temochka
    Commented Jan 19, 2021 at 1:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .