Class: Neo4j::Core::Index::UniqueFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/neo4j-core/index/unique_factory.rb

Overview

A Utility class that can be used to make it easier to create unique entities. It uses Indexer#put_if_absent.

Examples:

index = index_for_type(:exact)
Neo4j::Core::Index::UniqueFactory.new(:email, index) { |k,v| Neo4j::Node.new(k => v) }.get_or_create(:email, '[email protected]')

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(key, index) { ... } ⇒ UniqueFactory

Returns a new instance of UniqueFactory.

Parameters:

  • key (Symbol)

    only one key is possible

  • index (Java::Neo4j)

    the lucene index (see #index_for_type)

Yields:

  • a proc for initialize each created entity



18
19
20
21
22
# File 'lib/neo4j-core/index/unique_factory.rb', line 18

def initialize(key, index, &entity_creator_block)
  @key = key
  @index = index
  @entity_creator_block = entity_creator_block || Proc.new{|k,v| Neo4j::Node.new(key.to_s => v)}
end

Instance Method Details

#get_or_create(key, value, props = nil) { ... } ⇒ Object

Get the indexed entity, creating it (exactly once) if no indexed entity exists. There must be an index on the key. Must not be called inside a transaction.

Parameters:

  • key (Symbol)

    the key to find the entity under in the index.

  • value (String, Fixnum, Float)

    the value the key is mapped to for the entity in the index.

  • props (Hash) (defaults to: nil)

    optional properties that the entity will have if created

Yields:

  • optional, make it possible to initialize the created node in a block

Raises:

  • an exception if a transaction is running



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/neo4j-core/index/unique_factory.rb', line 32

def get_or_create(key, value, props=nil, &init_block)
  raise "Transaction already running, can't use get_or_create" if Neo4j.db.graph.respond_to?(:transactionRunning) && Neo4j.db.graph.transactionRunning

  tx = Neo4j::Transaction.new
  result = @index.get(key.to_s, value).get_single
  return result if result

  created = @entity_creator_block.call(key,value)
  result = @index.put_if_absent(created._java_entity, key.to_s, value)
  if result.nil?
    props.each_pair{|k,v| created[k.to_s] = v} if props
    init_block.call(result) if init_block
    result = created
  else
    created.del
  end
  tx.success
  result
ensure
  tx && tx.finish
end