Skip to content

Commit ead47a6

Browse files
committed
v0.1 release
* Added batch support, for much faster intiialization of current DB or reindexing all DB. * Dropped indexes per model, instead, using `node_auto_index` and `relationship_auto_index`, letting Neo4j auto index objects. * One `neo_save` method instead of `neo_create` and `neo_update`. It takes care of inserting or updating.
1 parent 2b1468b commit ead47a6

20 files changed

Lines changed: 1033 additions & 218 deletions

CHANGELOG.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,38 @@
1+
## v0.1
2+
3+
* Added batch support, for much faster intiialization of current DB or reindexing all DB.
4+
* Dropped indexes per model, instead, using `node_auto_index` and `relationship_auto_index`, letting Neo4j auto index objects.
5+
* One `neo_save` method instead of `neo_create` and `neo_update`. It takes care of inserting or updating.
6+
7+
### Breaking changes:
8+
9+
Model indexes (such as `users_index`) are now turned off by default. Instead, Neoid uses Neo4j's auto indexing feature.
10+
11+
In order to have the model indexes back, use this in your configuration:
12+
13+
```ruby
14+
Neoid.configure do |c|
15+
c.enable_per_model_indexes = true
16+
end
17+
```
18+
19+
This will turn on for all models.
20+
21+
You can turn off for a specific model with:
22+
23+
```ruby
24+
class User < ActiveRecord::Base
25+
include Neoid::Node
26+
27+
neoidable enable_model_index: false do |c|
28+
end
29+
end
30+
```
31+
32+
## v0.0.51
33+
34+
* Releasing Neoid as a gem.
35+
136
## v0.0.41
237

338
* fixed really annoying bug caused by Rails design -- Rails doesn't call `after_destroy` when assigning many to many relationships to a model, like `user.movies = [m1, m2, m3]` or `user.update_attributes(params[:user])` where it contains `params[:user][:movie_ids]` list (say from checkboxes), but it DOES CALL after_create for the new relationships. the fix adds after_remove callback to the has_many relationships, ensuring neo4j is up to date with all changes, no matter how they were committed

README.md

Lines changed: 148 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
[![Build Status](https://secure.travis-ci.org/elado/neoid.png)](http://travis-ci.org/elado/neoid)
44

55

6-
76
Make your ActiveRecords stored and searchable on Neo4j graph database, in order to make fast graph queries that MySQL would crawl while doing them.
87

98
Neoid to Neo4j is like Sunspot to Solr. You get the benefits of Neo4j speed while keeping your schema on your plain old RDBMS.
@@ -12,18 +11,21 @@ Neoid doesn't require JRuby. It's based on the great [Neography](https://github.
1211

1312
Neoid offers querying Neo4j for IDs of objects and then fetch them from your RDBMS, or storing all desired data on Neo4j.
1413

14+
**Important: Heroku Support is not available because Herokud doesn't support Gremlin. So until further notice, easiest way is to self host a Neo4j on EC2 in the same zone, and connect from your dyno to it**
15+
16+
## Changelog
17+
18+
[See Changelog](https://github.com/elado/neoid/blob/master/CHANGELOG.md)
1519

1620

1721
## Installation
1822

1923
Add to your Gemfile and run the `bundle` command to install it.
2024

2125
```ruby
22-
gem 'neoid', '~> 0.0.51'
26+
gem 'neoid', '~> 0.1'
2327
```
2428

25-
Future versions may have breaking changes but will arrive with migration code.
26-
2729
**Requires Ruby 1.9.2 or later.**
2830

2931
## Usage
@@ -51,6 +53,11 @@ Neography.configure do |c|
5153
end
5254

5355
Neoid.db = $neo
56+
57+
Neoid.configure do |c|
58+
# should Neoid create sub-reference from the ref node (id#0) to every node-model? default: true
59+
c.enable_subrefs = true
60+
end
5461
```
5562

5663
`01_` in the file name is in order to get this file loaded first, before the models (initializers are loaded alphabetically).
@@ -71,9 +78,9 @@ class User < ActiveRecord::Base
7178
end
7279
```
7380

74-
This will help to create a corresponding node on Neo4j when a user is created, delete it when a user is destroyed, and update it if needed.
81+
This will help to create/update/destroy a corresponding node on Neo4j when changed are made a User model.
7582

76-
Then, you can customize what fields will be saved on the node in Neo4j, inside neoidable configuration:
83+
Then, you can customize what fields will be saved on the node in Neo4j, inside `neoidable` configuration, using `field`. You can also pass blocks to save content that's not a real column:
7784

7885
```ruby
7986
class User < ActiveRecord::Base
@@ -89,7 +96,6 @@ class User < ActiveRecord::Base
8996
end
9097
```
9198

92-
9399
#### Relationships
94100

95101
Let's assume that a `User` can `Like` `Movie`s:
@@ -151,7 +157,7 @@ class Like < ActiveRecord::Base
151157
end
152158
```
153159

154-
Neoid adds `neo_node` and `neo_relationships` to nodes and relationships, respectively.
160+
Neoid adds the metohds `neo_node` and `neo_relationships` to instances of nodes and relationships, respectively.
155161

156162
So you could do:
157163

@@ -169,46 +175,60 @@ rel.end_node # user.movies.first.neo_node
169175
rel.rel_type # 'likes'
170176
```
171177

172-
## Index for Full-Text Search
178+
#### Disabling auto saving to Neo4j:
173179

174-
Using `search` block inside a `neoidable` block, you can store certain fields.
180+
If you'd like to save nodes manually rather than after_save, use `auto_index: false`:
175181

176182
```ruby
177-
# movie.rb
178-
179-
class Movie < ActiveRecord::Base
183+
class User < ActiveRecord::Base
180184
include Neoid::Node
181-
182-
neoidable do |c|
183-
c.field :slug
184-
c.field :name
185-
186-
c.search do |s|
187-
# full-text index fields
188-
s.fulltext :name
189-
s.fulltext :description
190-
191-
# just index for exact matches
192-
s.index :year
193-
end
185+
186+
neoidable auto_index: false do |c|
194187
end
195188
end
196-
```
197189

198-
Records will be automatically indexed when inserted or updated.
190+
user = User.create!(name: "Elad") # no node is created in Neo4j!
191+
192+
user.neo_save # now there is!
193+
```
199194

200195
## Querying
201196

202197
You can query with all [Neography](https://github.com/maxdemarzi/neography)'s API: `traverse`, `execute_query` for Cypher, and `execute_script` for Gremlin.
203198

199+
### Basics:
200+
201+
#### Finding a node by ID
202+
203+
Nodes and relationships are auto indexed in the `node_auto_index` and `relationship_auto_index` indexes, where the key is `Neoid::UNIQUE_ID_KEY` (which is 'neoid_unique_id') and the value is a combination of the class name and model id, `Movie:43`, this value is accessible with `model.neo_unique_id`. So use the constant and this method, never rely on assebling those values on your own because they might change in the future.
204+
205+
That means, you can query like this:
206+
207+
```ruby
208+
Neoid.db.get_node_auto_index(Neoid::UNIQUE_ID_KEY, user.neo_unique_id)
209+
# => returns a Neography hash
210+
211+
Neoid::Node.from_hash(Neoid.db.get_node_auto_index(Neoid::UNIQUE_ID_KEY, user.neo_unique_id))
212+
# => returns a Neography::Node
213+
```
214+
215+
#### Finding all nodes of type
216+
217+
If Subreferences are enabled, you can get the subref node and then get all attached nodes:
218+
219+
```ruby
220+
Neoid.ref_node.outgoing('users_subref').first.outgoing('users_subref').to_a
221+
# => this, according to Neography, returns an array of Neography::Node so no conversion is needed
222+
```
223+
204224
### Gremlin Example:
205225

206226
These examples query Neo4j using Gremlin for IDs of objects, and then fetches them from ActiveRecord with an `in` query.
207227

208228
Of course, you can store using the `neoidable do |c| c.field ... end` all the data you need in Neo4j and avoid querying ActiveRecord.
209229

210230

211-
**Most popular categories**
231+
**Most liked movies**
212232

213233
```ruby
214234
gremlin_query = <<-GREMLIN
@@ -228,15 +248,18 @@ movie_ids = Neoid.db.execute_script(gremlin_query)
228248
Movie.where(id: movie_ids)
229249
```
230250

231-
Assuming we have another `Friendship` model which is a relationship with start/end nodes of `user` and type of `friends`,
251+
*Side note: the resulted movies won't be sorted by like count because the RDBMS won't necessarily do it as we passed a list of IDs. You can sort it yourself with array manipulation, since you have the ids.*
252+
232253

233254
**Movies of user friends that the user doesn't have**
234255

256+
Let's assume we have another `Friendship` model which is a relationship with start/end nodes of `user` and type of `friends`,
257+
235258
```ruby
236259
user = User.find(1)
237260

238261
gremlin_query = <<-GREMLIN
239-
u = g.idx('users_index')[[ar_id:user_id]].next()
262+
u = g.idx('node_auto_index').get(unique_id_key, user_unique_id).next()
240263
movies = []
241264
242265
u
@@ -246,15 +269,42 @@ gremlin_query = <<-GREMLIN
246269
.except(movies).collect{it.ar_id}
247270
GREMLIN
248271

249-
movie_ids = Neoid.db.execute_script(gremlin_query, user_id: user.id)
272+
movie_ids = Neoid.db.execute_script(gremlin_query, unique_id_key: Neoid::UNIQUE_ID_KEY, user_unique_id: user.neo_unique_id)
250273

251274
Movie.where(id: movie_ids)
252275
```
253276

254-
`.next()` is in order to get a vertex object which we can actually query on.
277+
## Full Text Search
255278

279+
### Index for Full-Text Search
256280

257-
### Full Text Search
281+
Using `search` block inside a `neoidable` block, you can store certain fields.
282+
283+
```ruby
284+
# movie.rb
285+
286+
class Movie < ActiveRecord::Base
287+
include Neoid::Node
288+
289+
neoidable do |c|
290+
c.field :slug
291+
c.field :name
292+
293+
c.search do |s|
294+
# full-text index fields
295+
s.fulltext :name
296+
s.fulltext :description
297+
298+
# just index for exact matches
299+
s.index :year
300+
end
301+
end
302+
end
303+
```
304+
305+
Records will be automatically indexed when inserted or updated.
306+
307+
### Querying a Full-Text Search index
258308

259309
```ruby
260310
# will match all movies with full-text match for name/description. returns ActiveRecord instanced
@@ -270,14 +320,63 @@ Neoid.neo_search([Movie, User], "hello")
270320
Movie.neo_search(year: 2013).results
271321
```
272322

323+
Full text search with Neoid is very limited and is likely not to develop more than this basic functionality. I strongly recommend using gems like Sunspot over Solr.
324+
325+
## Batches
326+
327+
Neoid has a batch ability, that is good for mass updateing/inserting of nodes/relationships. It sends batched requests to Neography, and takes care of type conversion (neography batch returns hashes and other primitive types) and "after" actions (via promises).
328+
329+
A few examples, easy to complex:
330+
331+
```ruby
332+
Neoid.batch(batch_size: 100) do
333+
User.all.each(&:neo_save)
334+
end
335+
```
336+
With `then`:
337+
338+
```ruby
339+
User.first.name # => "Elad"
340+
341+
Neoid.batch(batch_size: 100) do
342+
User.all.each(&:neo_save)
343+
end.then do |results|
344+
# results is an array of the script results from neo4j REST.
345+
346+
results[0].name # => "Elad"
347+
end
348+
```
349+
350+
*Nodes and relationships in the results are automatically converted to Neography::Node and Neography::Relationship, respectively.*
351+
352+
With individual `then` as well as `then` for the entire batch:
353+
354+
```ruby
355+
Neoid.batch(batch_size: 30) do |batch|
356+
(1..90).each do |i|
357+
(batch << [:create_node, { name: "Hello #{i}" }]).then { |result| puts result.name }
358+
end
359+
end.then do |results|
360+
puts results.collect(&:name)
361+
end
362+
```
363+
364+
When in a batch, `neo_save` adds gremlin scripts to a batch, instead of running them immediately. The batch flushes whenever the `batch_size` option is met.
365+
So even if you have 20000 users, Neoid will insert/update in smaller batches. Default `batch_size` is 200.
366+
367+
273368
## Inserting records of existing app
274369

275-
If you have an existing database and just want to integrate Neoid, configure the `neoidable`s and run in a rake task or console
370+
If you have an existing database and just want to integrate Neoid, configure the `neoidable`s and run in a rake task or console.
371+
372+
Use batches! It's free, and much faster. Also, you should use `includes` to incude the relationship edges on relationship entities, so it doesn't query the DB on each relationship.
276373

277374
```ruby
278-
[ Like.includes(:user).includes(:movie), OtherRelationshipModel ].each { |model| model.all.each(&:neo_update) }
375+
Neoid.batch do
376+
[ Like.includes(:user).includes(:movie), OtherRelationshipModel.includes(:from_model).includes(:to_model) ].each { |model| model.all.each(&:neo_save) }
279377

280-
NodeModel.all.each(&:neo_update)
378+
NodeModel.all.each(&:neo_save)
379+
end
281380
```
282381

283382
This will loop through all of your relationship records and generate the two edge nodes along with a relationship (eager loading for better performance).
@@ -289,30 +388,32 @@ Better interface for that in the future.
289388

290389
## Behind The Scenes
291390

292-
Whenever the `neo_node` on nodes or `neo_relationship` on relationships is called, Neoid checks if there's a corresponding node/relationship in Neo4j. If not, it does the following:
391+
Whenever the `neo_node` on nodes or `neo_relationship` on relationships is called, Neoid checks if there's a corresponding node/relationship in Neo4j (with the auto indexes). If not, it does the following:
293392

294393
### For Nodes:
295394

296-
1. Ensures there's a sub reference node (read [here](http://docs.neo4j.org/chunked/stable/tutorials-java-embedded-index.html) about sub reference nodes)
395+
1. Ensures there's a sub reference node (read [here](http://docs.neo4j.org/chunked/stable/tutorials-java-embedded-index.html) about sub references), if that option is on.
297396
2. Creates a node based on the ActiveRecord, with the `id` attribute and all other attributes from `neoidable`'s field list
298397
3. Creates a relationship between the sub reference node and the newly created node
299-
4. Adds the ActiveRecord `id` to a node index, pointing to the Neo4j node id, for fast lookup in the future
398+
4. Auto indexes a node in the auto index, for fast lookup in the future
300399

301-
Then, when it needs to find it again, it just seeks the node index with that ActiveRecord id for its neo node id.
400+
Then, when it needs to find it again, it just seeks the auto index with that ActiveRecord id.
302401

303402
### For Relationships:
304403

305-
Like Nodes, it uses an index (relationship index) to look up a relationship by ActiveRecord id
404+
Like Nodes, it uses an auto index, to look up a relationship by ActiveRecord id
306405

307406
1. With the options passed in the `neoidable`, it fetches the `start_node` and `end_node`
308407
2. Then, it calls `neo_node` on both, in order to create the Neo4j nodes if they're not created yet, and creates the relationship with the type from the options.
309-
3. Add the relationship to the relationship index.
408+
3. Adds the relationship to the relationship index.
310409

311410
## Testing
312411

313412
In order to test your app or this gem, you need a running Neo4j database, dedicated to tests.
314413

315-
I use port 7574 for this. To run another database locally:
414+
I use port 7574 for testing.
415+
416+
To run another database locally (read [here](http://docs.neo4j.org/chunked/1.9.M03/server-installation.html#_multiple_server_instances_on_one_machine) too):
316417

317418
Copy the entire Neo4j database folder to a different location,
318419

@@ -344,7 +445,7 @@ end
344445

345446
## Testing This Gem
346447

347-
Just run `rake` from the gem folder.
448+
Run the Neo4j DB on port 7574, and run `rake` from the gem folder.
348449

349450
## Contributing
350451

@@ -356,9 +457,9 @@ Please create a [new issue](https://github.com/elado/neoid/issues) if you run in
356457
Unfortunately, as for now, Neo4j add-on on Heroku doesn't support Gremlin. Therefore, this gem won't work on Heroku's add on. You should self-host a Neo4j instance on an EC2 or any other server.
357458

358459

359-
## To Do
460+
## TO DO
360461

361-
[To Do](https://github.com/elado/neoid/blob/master/TODO.md)
462+
[TO DO](HTTPS://GITHUB.COM/ELADO/NEOID/BLOB/MASTER/TODO.MD)
362463

363464

364465
---

TODO.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
# Neoid - To Do
22

3-
* Allow to disable sub reference nodes through options
43
* Execute queries/scripts from model and not Neography (e.g. `Movie.neo_gremlin(gremlin_query)` with query that outputs IDs, returns a list of `Movie`s)
54
* Rake task to index all nodes and relatiohsips in Neo4j
6-
* Test update node

0 commit comments

Comments
 (0)