2

I have a bunch of records containing business names and I wish to do a query to find all the duplicates. How can this be done?

{:business/name "<>"}

1 Answer 1

4

If you're trying to enforce uniqueness on the attribute value you should look at the :db/unique schema attribute instead.

To find the duplicated values and how often they repeat, use:

(->> (d/datoms db :aevt :business/name)
   (map :v)
   (frequencies)
   (filter #(> (second %) 1)))

which uses the datomic.api/datoms API to access the raw AEVT index to stream :business/name attribute values, calculate their frequency and filter them based on some criteria i.e. more than one occurrence. You can also achieve the same result using datalog and aggregation functions:

(->> (d/q '[:find (frequencies ?v)
      :with ?e
      :in $ ?a
      :where [?e ?a ?v]]
    db :business/name)
 (ffirst)
 (filter #(> (second %) 1)))

To find the entities with duplicated attribute values, use:

(->> (d/datoms db :aevt :business/name)
   (group-by :v)
   (filter #(> (count (second %)) 1))
   (mapcat second)
   (map :e))

which also leverages the d/datoms API to accomplish it. For a full code sample, including datalog implementations, see https://gist.github.com/a2ndrade/5641681

3
  • Thanks! Basically, I'm trying to establish uniqueness after the data has been loaded in... Maybe that's not such a good idea..
    – zcaudate
    May 24, 2013 at 13:23
  • It's a bad idea unless your database is so large than :business/name values can't fit in the transactor's memory. In that case, uniqueness constraints will dominate transaction times as the transactor may need to query/decompress a big number of segments from storage, which also may push out other hot data from cache.
    – a2ndrade
    May 26, 2013 at 14:14
  • 1
    @a2ndrade what about duplicates based on multiple datoms? :busines/name and :business/zipcode? Jan 28, 2015 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.