Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Full-text and fuzzy search with Titanium
(ns titanium-demo.core
(:require [clojure.java.io :as io]
[clojurewerkz.titanium.graph :as tg]
[clojurewerkz.titanium.schema :as scm]
[clojurewerkz.titanium.vertices :as tv]))
(defn generate-config
"Generate a configuration map to use BerkeleyDB and Lucene
with data stored in the given directory."
[dir]
{"storage.backend" "berkeleyje"
"storage.directory" (.getPath (io/file dir "bdb"))
"index.search.backend" "lucene"
"index.search.directory" (.getPath (io/file dir "lucene"))})
(defn init-graph
[path]
(let [graph (tg/open (generate-config path))]
(scm/with-management-system [mgmt graph]
(scm/make-property-key mgmt "name" String)
(scm/build-composite-index mgmt "ixName" :vertex ["name"] :unique? true)
(scm/make-property-key mgmt "description" String)
(scm/build-mixed-index mgmt "ixDescription" :vertex ["description"] "search"))
graph))
(defn load-data
[graph]
(tg/with-transaction [tx graph]
(doseq [[name description]
(partition 2
["Adams"
"The top student in David Copperfield's class at Strong's school in Cantebury"
"Aged Parent"
"The very old and very deaf father of John Wemmick in Great Expectations"
"Arabella Allen"
"The sister of Benjamin Allen, and eventually Mr Winkle's wife, in The Pickwick Papers"
"Benjamin Allen"
"A medical student and later a doctor in The Pickwick Papers. Brother of Arabella Allen. "
"Artful Dodger"
"A street-smart pickpocket and criminal in Oliver Twist"])]
(tv/create! tx {:name name :description description}))))
(def graph (init-graph "/tmp/dickens.123"))
(load-data graph)
;; A basic full-text query
(map (fn [result] (-> (.getElement result) (tv/get :name)))
(.vertices (.indexQuery graph "ixDescription" "v.description:sister")))
;; Fuzzy search on "sistar"
(map (juxt #(-> (.getElement %) (tv/get :name)) #(.getScore %))
(.vertices (.indexQuery graph "ixDescription" "v.description:sistar~")))
;; Entries containing any of the words "student" or "wife"
(map #(-> (.getElement %) (tv/get :name))
(.vertices (.indexQuery graph "ixDescription" "v.description:(student wife)")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment