Possible smart rule to handle complex tag query

I have several thousand items exported from Readwise Reader. They are all in a specific group, and are all tagged with “Readwise” and “Articles” and whatever other tags they were given in Readwise.

I would like a smart group matching items with those two tags, but no others. (alternatively, it could match Readwise and the number of tags could be exactly 2)

I see from elsewhere on the forum that there isn’t a straightforward way to do this. Is it possible to write a smart rule with a script that would, say, match everything with those 2 tags, then have the script evaluate whether there are any other tags in addition, and tag those items otherwise untagged items “TAGME” or replicate them to an “TAGME” group or something?

I would prefer not to use AI for this - is there an alternative?

1 Like

A script like

function performsmartrule(records) {
  records.filter(r => r.tags().length === 2).forEach(r => r.tags = r.tags.concat('WhatEver’))
}

added to the execute script action in a smart rule would tag all records selected by the rule’s condition having exactly two tags with "WhatEver“.

Is that what you’re after?

1 Like

Almost everything can be done without AI, except writing lots of slop :rofl:

property requiredTagNames : {"Readwise", "Articles"}
property markerTagName : "TAGME"

on performSmartRule(theRecords)
	tell application id "DNtp"
		set requiredCount to count of requiredTagNames
		repeat with theRecord in theRecords
			set existingTags to tags of theRecord
			if existingTags is not missing value and (count of existingTags) is requiredCount then
				set shouldMark to true
				repeat with requiredTag in requiredTagNames
					if existingTags does not contain requiredTag then
						set shouldMark to false
						exit repeat
					end if
				end repeat
				if shouldMark then set tags of theRecord to existingTags & {markerTagName}
			end if
		end repeat
	end tell
end performSmartRule
4 Likes

Huh. I wasn’t aware that you can’t search for records matching only the specified tags. Guess I never needed that.

It turns out you can effectively perform this search in scripts with a whose filter:

const exactTagsMatch = ["tag A", "tag B"];
const records = database.contents.whose({
	tags: {'=': exactTagsMatch}
});

That doesn’t help with smart groups/rules. But a smart rule script is not necessary if marking the items is a one-time operation.

(() => {
	const app = Application("DEVONthink");
	app.includeStandardAdditions = true;
	const exactTagsMatch = ["Readwise", "Articles"];
	const records = app.currentDatabase.contents.whose({
		tags: {'=': exactTagsMatch}
	});
	records().forEach( r =>
		r.tags = r.tags().concat("TAGME"));
})()
1 Like