DataScript / datahike rules returning nothing

242 views Asked by At

I try to search for a string in more than one field of a database in datahike. So far without success. Here is my best effort approach so far:

(ns my.ns
  (:require [clojure.string :as st]
            [datahike.api :as dh]))

(def card-db [[1 :card/name "CardA"]
              [1 :card/text "Text of CardA mentioning CardB"]
              [2 :card/name "CardB"]
              [2 :card/text "A mystery"]])

(def rules '[
             [
              (matches-name ?ent ?fn ?str)
              [?ent :card/name ?name]
              (?fn ?name ?str)]
             [(matches-text ?ent ?fn ?str)
              [?ent :card/text ?text]
              (?fn ?text ?str)
              ]
             ])

(defn my-search [db search-strs]
  (dh/q '[:find ?e
          :in $ % ?fn [?str ...]
          :where
          [?e :card/name ?name]

          #_[(?fn ?name ?str)] ;; this finds CardB

          (or
           (matches-name ?e ?fn ?str)
           (matches-text ?e ?fn ?str)
           ) ;; this finds nothing
          ]
        db rules st/includes? search-strs))
#_(count (my-search card-db ["CardB"]))

Expected result: 2

Actual result: 0

The solution needn't use rules as far as I'm concerned. It should just return a match if a string is found in at least one of multiple fields.

I'm using [io.replikativ/datahike "0.1.1"]

1

There are 1 answers

0
Niki Tonsky On

DataScript doesn’t support or yet. I think Datahike does neither. But you can emulate it using rules. Try:

(def rules '[[(matches ?ent ?fn ?str)
              [?ent :card/name ?name]
              (?fn ?name ?str)]
             [(matches ?ent ?fn ?str)
              [?ent :card/text ?text]
              (?fn ?text ?str)]])

(defn my-search [db search-strs]
  (dh/q '[:find ?e
          :in $ % ?fn [?str ...]
          :where [?e :card/name ?name]
                 (matches ?e ?fn ?str)]
        db rules st/includes? search-strs))