├── .gitignore
├── README.md
├── SpringData-Neo4j
├── .classpath
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── .shell_history
├── README.md
└── src
│ └── com
│ └── hmkcode
│ ├── Main.java
│ ├── spring
│ └── spring.xml
│ ├── springdata
│ └── neo4j
│ │ └── GraphDB.java
│ └── vo
│ └── Person.java
├── index.html
├── mongodb-java
├── .classpath
├── .project
├── README.md
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── hmkcode
│ └── mongodb
│ ├── Main.java
│ ├── MapReduce.java
│ └── Query.java
├── mongodb-springdata
├── .classpath
├── README.md
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── hmkcode
│ ├── spring
│ ├── data
│ │ └── mongodb
│ │ │ └── Main.java
│ └── spring.xml
│ └── vo
│ ├── Address.java
│ └── Person.java
└── spring-data-neo4j-person-friends
├── .classpath
├── .project
├── .settings
└── org.eclipse.jdt.core.prefs
├── .shell_history
├── README.md
└── src
└── com
└── hmkcode
├── FriendMaker.java
├── Main.java
└── spring
├── config
└── spring_aspects.xml
└── data
└── neo4j
├── entity
└── Person.java
├── repository
└── PersonRepository.java
└── service
└── PersonService.java
/.gitignore:
--------------------------------------------------------------------------------
1 | #################
2 | ## Eclipse
3 | #################
4 |
5 | *.pydevproject
6 | .project
7 | .metadata
8 | bin/
9 | tmp/
10 | *.tmp
11 | *.bak
12 | *.swp
13 | *~.nib
14 | local.properties
15 | .classpath
16 | .settings/
17 | .loadpath
18 |
19 | # External tool builders
20 | .externalToolBuilders/
21 |
22 | # Locally stored "Eclipse launch configurations"
23 | *.launch
24 |
25 | # CDT-specific
26 | .cproject
27 |
28 | # PDT-specific
29 | .buildpath
30 |
31 |
32 | #################
33 | ## Visual Studio
34 | #################
35 |
36 | ## Ignore Visual Studio temporary files, build results, and
37 | ## files generated by popular Visual Studio add-ons.
38 |
39 | # User-specific files
40 | *.suo
41 | *.user
42 | *.sln.docstates
43 |
44 | # Build results
45 | [Dd]ebug/
46 | [Rr]elease/
47 | *_i.c
48 | *_p.c
49 | *.ilk
50 | *.meta
51 | *.obj
52 | *.pch
53 | *.pdb
54 | *.pgc
55 | *.pgd
56 | *.rsp
57 | *.sbr
58 | *.tlb
59 | *.tli
60 | *.tlh
61 | *.tmp
62 | *.vspscc
63 | .builds
64 | *.dotCover
65 |
66 | ## TODO: If you have NuGet Package Restore enabled, uncomment this
67 | #packages/
68 |
69 | # Visual C++ cache files
70 | ipch/
71 | *.aps
72 | *.ncb
73 | *.opensdf
74 | *.sdf
75 |
76 | # Visual Studio profiler
77 | *.psess
78 | *.vsp
79 |
80 | # ReSharper is a .NET coding add-in
81 | _ReSharper*
82 |
83 | # Installshield output folder
84 | [Ee]xpress
85 |
86 | # DocProject is a documentation generator add-in
87 | DocProject/buildhelp/
88 | DocProject/Help/*.HxT
89 | DocProject/Help/*.HxC
90 | DocProject/Help/*.hhc
91 | DocProject/Help/*.hhk
92 | DocProject/Help/*.hhp
93 | DocProject/Help/Html2
94 | DocProject/Help/html
95 |
96 | # Click-Once directory
97 | publish
98 |
99 | # Others
100 | [Bb]in
101 | [Oo]bj
102 | sql
103 | TestResults
104 | *.Cache
105 | ClientBin
106 | stylecop.*
107 | ~$*
108 | *.dbmdl
109 | Generated_Code #added for RIA/Silverlight projects
110 |
111 | # Backup & report files from converting an old project file to a newer
112 | # Visual Studio version. Backup files are not needed, because we have git ;-)
113 | _UpgradeReport_Files/
114 | Backup*/
115 | UpgradeLog*.XML
116 |
117 |
118 |
119 | ############
120 | ## Windows
121 | ############
122 |
123 | # Windows image file caches
124 | Thumbs.db
125 |
126 | # Folder config file
127 | Desktop.ini
128 |
129 |
130 | #############
131 | ## Python
132 | #############
133 |
134 | *.py[co]
135 |
136 | # Packages
137 | *.egg
138 | *.egg-info
139 | dist
140 | build
141 | eggs
142 | parts
143 | bin
144 | var
145 | sdist
146 | develop-eggs
147 | .installed.cfg
148 |
149 | # Installer logs
150 | pip-log.txt
151 |
152 | # Unit test / coverage reports
153 | .coverage
154 | .tox
155 |
156 | #Translations
157 | *.mo
158 |
159 | #Mr Developer
160 | .mr.developer.cfg
161 |
162 | # Mac crap
163 | .DS_Store
164 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | nosql
2 | =====
3 |
4 | Neo4j + Mongodb sample codes
--------------------------------------------------------------------------------
/SpringData-Neo4j/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/SpringData-Neo4j/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | SpringData-Neo4j
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/SpringData-Neo4j/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Mon Mar 11 21:11:33 AST 2013
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.6
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.source=1.6
13 |
--------------------------------------------------------------------------------
/SpringData-Neo4j/.shell_history:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hmkcode/nosql/3f41b71e57fdacf14a485d349c1857a861ff24b2/SpringData-Neo4j/.shell_history
--------------------------------------------------------------------------------
/SpringData-Neo4j/README.md:
--------------------------------------------------------------------------------
1 | Spring Data Neo4j
2 | =================
3 |
4 | This is a simple example showing how to code for Neo4j using Spring Data Neo4j.
5 |
6 | * Convert POJO to Neo4j entity --> @NodeEntity
7 | * Create and index --> @Indexed
8 | * Relation that has no property can be annotated --> @RelatedTo
9 | * Noe4jTemplate will be used to interact with the db (store & retrieve)
10 | * Transaction will be handeled manually i.e. without using @Transactional
11 |
--------------------------------------------------------------------------------
/SpringData-Neo4j/src/com/hmkcode/Main.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode;
2 |
3 | import org.springframework.context.ApplicationContext;
4 | import org.springframework.context.support.ClassPathXmlApplicationContext;
5 |
6 | import com.hmkcode.springdata.neo4j.GraphDB;
7 |
8 | public class Main{
9 |
10 | public static void main(String[] args){
11 | ApplicationContext context = new ClassPathXmlApplicationContext("com/hmkcode/spring/spring.xml");
12 | GraphDB db = (GraphDB)context.getBean("graphDB");
13 | db.buildDataModel();
14 |
15 | }
16 |
17 | }
--------------------------------------------------------------------------------
/SpringData-Neo4j/src/com/hmkcode/spring/spring.xml:
--------------------------------------------------------------------------------
1 |
2 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/SpringData-Neo4j/src/com/hmkcode/springdata/neo4j/GraphDB.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.springdata.neo4j;
2 |
3 | import org.neo4j.graphdb.GraphDatabaseService;
4 | import org.neo4j.graphdb.Transaction;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.data.neo4j.support.Neo4jTemplate;
7 |
8 | import com.hmkcode.vo.*;
9 |
10 |
11 | public class GraphDB {
12 |
13 | @Autowired
14 | private Neo4jTemplate template;
15 |
16 | public void buildDataModel(){
17 | registerShutdownHook( template.getGraphDatabaseService());
18 | Transaction tx = template.getGraphDatabase().beginTx();
19 | try{
20 | Person p1 = new Person();
21 | p1.setId("person-01");
22 | p1.setName("John");
23 | Person p2 = new Person();
24 | p2.setId("person-02");
25 | p2.setName("Brit");
26 | Person p3 = new Person();
27 | p3.setId("person-03");
28 | p3.setName("Adam");
29 |
30 | p2.addFriend(p3);
31 | p1.addFriend(p2);
32 |
33 | Person savedPerson = template.save(p1);
34 |
35 | Person loadedPerson = template.findOne(savedPerson.getNodeId(), Person.class);
36 |
37 | System.out.println("User: "+loadedPerson.getNodeId());
38 | tx.success();
39 | tx.finish();
40 | }finally{
41 | System.out.println("finally");
42 | }
43 | }
44 |
45 | public Neo4jTemplate getTemplate() {
46 | return template;
47 | }
48 |
49 | public void setTemplate(Neo4jTemplate template) {
50 | this.template = template;
51 | }
52 | private static void registerShutdownHook( final GraphDatabaseService graphDb )
53 | {
54 | Runtime.getRuntime().addShutdownHook( new Thread()
55 | {
56 | @Override
57 | public void run()
58 | {
59 | graphDb.shutdown();
60 |
61 | }
62 | } );
63 | }
64 |
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/SpringData-Neo4j/src/com/hmkcode/vo/Person.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.vo;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | import org.neo4j.graphdb.Direction;
7 | import org.springframework.data.neo4j.annotation.GraphId;
8 | import org.springframework.data.neo4j.annotation.Indexed;
9 | import org.springframework.data.neo4j.annotation.NodeEntity;
10 | import org.springframework.data.neo4j.annotation.RelatedTo;
11 |
12 |
13 |
14 | @NodeEntity
15 | public class Person {
16 |
17 |
18 | @GraphId
19 | private Long nodeId;
20 |
21 | @Indexed
22 | private String id;
23 | private String name;
24 |
25 | public Person(){}
26 |
27 | @RelatedTo(type = "KNOW", direction = Direction.BOTH)
28 | private Set friends;
29 |
30 | public Long getNodeId() {
31 | return nodeId;
32 | }
33 |
34 | public void setNodeId(Long nodeId) {
35 | this.nodeId = nodeId;
36 | }
37 |
38 | public String getId() {
39 | return id;
40 | }
41 |
42 | public void setId(String id) {
43 | this.id = id;
44 | }
45 |
46 | public String getName() {
47 | return name;
48 | }
49 |
50 | public void setName(String name) {
51 | this.name = name;
52 | }
53 |
54 | public Set getFriends() {
55 | return friends;
56 | }
57 |
58 | public void setFriends(Set friends) {
59 | this.friends = friends;
60 | }
61 |
62 | public void addFriend(Person person){
63 | if(friends == null)
64 | friends = new HashSet();
65 | friends.add(person);
66 | }
67 |
68 |
69 |
70 |
71 |
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Untitled 1
7 |
8 |
9 |
10 | TEST
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/mongodb-java/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/mongodb-java/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | mongodb-java
4 | NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.
5 |
6 |
7 |
8 | org.eclipse.jdt.core.javabuilder
9 |
10 |
11 |
12 | org.eclipse.jdt.core.javanature
13 |
14 |
--------------------------------------------------------------------------------
/mongodb-java/README.md:
--------------------------------------------------------------------------------
1 | mongodb + java
2 | ==============
3 |
4 | This is a simple example shows how to interact with mongodb from java application.
5 |
6 | -Hani
7 |
--------------------------------------------------------------------------------
/mongodb-java/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.hmkcode
6 | mongodb-java
7 | 1.0-SNAPSHOT
8 | jar
9 |
10 | mongodb-java
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 | org.mongodb
20 | mongo-java-driver
21 | 2.10.1
22 |
23 |
24 |
25 |
26 |
27 |
28 | org.codehaus.mojo
29 | exec-maven-plugin
30 | 1.2.1
31 |
32 | com.hmkcode.mongodb.Main
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/mongodb-java/src/main/java/com/hmkcode/mongodb/Main.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.mongodb;
2 |
3 | import java.net.UnknownHostException;
4 | import java.text.DateFormat;
5 | import java.text.ParseException;
6 | import java.text.SimpleDateFormat;
7 | import java.util.Calendar;
8 | import java.util.Date;
9 | import java.util.HashMap;
10 | import java.util.LinkedList;
11 |
12 | import com.mongodb.BasicDBObject;
13 | import com.mongodb.DB;
14 | import com.mongodb.DBCollection;
15 | import com.mongodb.DBCursor;
16 | import com.mongodb.MongoClient;
17 | import com.mongodb.MongoException;
18 |
19 | /**
20 | * Java + MongoDB Simple Example
21 | *
22 | */
23 | public class Main {
24 |
25 |
26 | static String array_names[] = {"John","Tim","Brit","Robin","Smith","Lora","Jennifer","Lyla","Victor","Adam"};
27 |
28 | static String array_address[][] ={
29 | {"US", "FL", " Miami"},
30 | {"US", "FL", " Orlando"},
31 | {"US", "CA", "San Diego"},
32 | {"US", "FL", " Orlando"},
33 | {"US", "FL", " Orlando"},
34 | {"US", "NY", "New York"},
35 | {"US", "NY", "Buffalo"},
36 | {"US", "TX", " Houston"},
37 | {"US", "CA", "San Diego"},
38 | {"US", "TX", " Houston"}
39 | };
40 |
41 | public static void main(String[] args) {
42 |
43 | try {
44 |
45 | // Connect to mongodb
46 | MongoClient mongo = new MongoClient("localhost", 27017);
47 |
48 | // get database
49 | // if database doesn't exists, mongodb will create it for you
50 | DB db = mongo.getDB("test");
51 |
52 | // get collection
53 | // if collection doesn't exists, mongodb will create it for you
54 | DBCollection collection = db.getCollection("person");
55 |
56 | /**** Insert ****/
57 | // create a document to store key and value
58 |
59 | BasicDBObject document ;
60 | String address[];
61 | for(int i = 0 ; i < array_names.length ; i++){
62 | document = new BasicDBObject();
63 | //value -> String
64 | document.append("name", array_names[i]);
65 | // value -> int
66 | document.append("age", (int)(Math.random()*60));
67 | // value -> date
68 | document.append("join", new Date());
69 | // value -> array
70 | document.append("friends", pickFriends());
71 |
72 | address = pickAddress();
73 | // value --> document
74 | document.append("address", new BasicDBObject("country",address[0])
75 | .append("state", address[1])
76 | .append("city", address[2]));
77 |
78 | collection.insert(document);
79 |
80 | }
81 |
82 |
83 | // get count
84 | System.out.println("All Persons: "+collection.getCount());
85 | //------------------------------------
86 | // get all document
87 | DBCursor cursor = collection.find();
88 | try {
89 | while(cursor.hasNext()) {
90 | System.out.println(cursor.next());
91 | }
92 | } finally {
93 | cursor.close();
94 | }
95 | //------------------------------------
96 |
97 | // get documents by query
98 | BasicDBObject query = new BasicDBObject("age", new BasicDBObject("$gt", 40));
99 |
100 | cursor = collection.find(query);
101 | System.out.println("Person with age > 40 --> "+cursor.count());
102 |
103 |
104 | /**** Update ****/
105 | //update documents found by query "age > 30" with udpateObj "age = 20"
106 | BasicDBObject newDocument = new BasicDBObject();
107 | newDocument.put("age", 20);
108 |
109 | BasicDBObject updateObj = new BasicDBObject();
110 | updateObj.put("$set", newDocument);
111 |
112 | collection.update(query, updateObj,false,true);
113 |
114 | /**** Find and display ****/
115 | cursor = collection.find(query);
116 | System.out.println("Person with age > 40 after update --> "+cursor.count());
117 |
118 |
119 | //get all again
120 | cursor = collection.find();
121 | try {
122 | while(cursor.hasNext()) {
123 | System.out.println(cursor.next());
124 | }
125 | } finally {
126 | cursor.close();
127 | }
128 |
129 | /**** Done ****/
130 | System.out.println("Done");
131 |
132 | } catch (UnknownHostException e) {
133 | e.printStackTrace();
134 | } catch (MongoException e) {
135 | e.printStackTrace();
136 | }
137 |
138 | }
139 | //----------------------------------------------------
140 | //These methods are just jused to build random data
141 | private static String[] pickFriends(){
142 | int numberOfFriends = (int) (Math.random()* 10);
143 | LinkedList friends = new LinkedList();
144 | int random = 0;
145 | while(friends.size() < numberOfFriends){
146 | random = (int) (Math.random()*10);
147 | if(!friends.contains(array_names[random]))
148 | friends.add(array_names[random]);
149 |
150 | }
151 | String a[] = {};
152 | return friends.toArray(a);
153 | }
154 | private static String[] pickAddress(){
155 | int random = (int) (Math.random()*10);
156 | return array_address[random];
157 | }
158 | }
--------------------------------------------------------------------------------
/mongodb-java/src/main/java/com/hmkcode/mongodb/MapReduce.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.mongodb;
2 |
3 | import java.net.UnknownHostException;
4 |
5 | import com.mongodb.DB;
6 | import com.mongodb.DBCollection;
7 | import com.mongodb.DBObject;
8 | import com.mongodb.MapReduceCommand;
9 | import com.mongodb.MapReduceOutput;
10 | import com.mongodb.MongoClient;
11 |
12 |
13 |
14 | /**
15 | * Java + MongoDB MapReduce count()
16 | *
17 | */
18 | public class MapReduce {
19 |
20 |
21 |
22 | public static void main(String[] args) {
23 |
24 |
25 | // Connect to mongodb
26 | MongoClient mongo = null;
27 | try {
28 | mongo = new MongoClient("localhost", 27017);
29 | } catch (UnknownHostException e) {
30 | // TODO Auto-generated catch block
31 | e.printStackTrace();
32 | }
33 |
34 | // get database
35 | // if database doesn't exists, mongodb will create it for you
36 | DB db = mongo.getDB("test");
37 |
38 | // get collection
39 | // if collection doesn't exists, mongodb will create it for you
40 | DBCollection collection = db.getCollection("person");
41 |
42 | String map ="function () {"+
43 | "emit('size', {count:1});"+
44 | "}";
45 |
46 | String reduce = "function (key, values) { "+
47 | " total = 0; "+
48 | " for (var i in values) { "+
49 | " total += values[i].count; "+
50 | " } "+
51 | " return {count:total} }";
52 |
53 | MapReduceCommand cmd = new MapReduceCommand(collection, map, reduce,
54 | null, MapReduceCommand.OutputType.INLINE, null);
55 |
56 | MapReduceOutput out = collection.mapReduce(cmd);
57 |
58 | for (DBObject o : out.results()) {
59 | System.out.println(o.toString());
60 | }
61 | System.out.println("Done");
62 |
63 |
64 |
65 | }
66 | }
67 |
68 |
--------------------------------------------------------------------------------
/mongodb-java/src/main/java/com/hmkcode/mongodb/Query.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.mongodb;
2 |
3 | import java.net.UnknownHostException;
4 | import java.util.Date;
5 | import java.util.regex.Pattern;
6 |
7 | import com.mongodb.BasicDBObject;
8 | import com.mongodb.DB;
9 | import com.mongodb.DBCollection;
10 | import com.mongodb.DBCursor;
11 | import com.mongodb.MongoClient;
12 | import com.mongodb.MongoException;
13 |
14 | /**
15 | * Java + MongoDB Simple Example
16 | *
17 | */
18 | public class Query {
19 | public static void main(String[] args) {
20 |
21 | try {
22 |
23 | // Connect to mongodb
24 | MongoClient mongo = new MongoClient("localhost", 27017);
25 |
26 | // get database
27 | // if database doesn't exists, mongodb will create it for you
28 | DB db = mongo.getDB("test");
29 |
30 | // get collection
31 | // if collection doesn't exists, mongodb will create it for you
32 | DBCollection collection = db.getCollection("person");
33 |
34 | DBCursor cursor;
35 | BasicDBObject query;
36 | //------------------------------------
37 | // ( 1 ) collection.find() --> get all document
38 | cursor = collection.find();
39 | System.out.println("( 1 ) .find()");
40 | System.out.println("results --> "+cursor.count());
41 | try {
42 | while(cursor.hasNext()) {
43 | System.out.println(cursor.next());
44 | }
45 | } finally {
46 | cursor.close();
47 | }
48 | System.out.println("---------------------------------");
49 | //------------------------------------
50 | // ( 2 ) collection.find({"age" : {"$gt" : 10}})) --> get documents by query
51 | String[] comparison_operators = {"$gt","$lt","$gte","$lte","$ne"};
52 | for(int p = 0 ; p < comparison_operators.length; p++){
53 | query = new BasicDBObject("age", new BasicDBObject(comparison_operators[p], 20));
54 | cursor = collection.find(query);
55 | System.out.println("( 2."+(p+1)+" ) .find({\"age\" : {\""+comparison_operators[p]+"\" : 20}})");
56 | System.out.println("results --> "+cursor.count());
57 | }
58 | System.out.println("---------------------------------");
59 | //------------------------------------
60 | // ( 3 ) collection.find({"name" : /j/}, {"name" : 1, "age" : 1,"_id":0}) --> get documents with some keys
61 | Pattern j = Pattern.compile("j", Pattern.CASE_INSENSITIVE);
62 | query = new BasicDBObject("name", j);
63 | BasicDBObject keys = new BasicDBObject("name", 1).append("age", 1).append("_id", 0);
64 | cursor = collection.find(query, keys);
65 | System.out.println("( 3 ) .find({\"name\" : /j/i}, {\"name\" : 1, \"age\" : 1,\"_id\":0})");
66 | System.out.println("results --> "+cursor.count());
67 | try {
68 | while(cursor.hasNext()) {
69 | System.out.println(cursor.next());
70 | }
71 | } finally {
72 | cursor.close();
73 | }
74 | System.out.println("---------------------------------");
75 | //-----------------------------------
76 | // ( 4 ) collection.find({"age" : {"$in" : [10,20,30]}})) --> get documents by query
77 | String[] or_operators = {"$in","$nin"};
78 | int[] age_array = {10,20,30};
79 | for(int p = 0 ; p < or_operators.length; p++){
80 | query = new BasicDBObject("age", new BasicDBObject(or_operators[p], age_array));
81 | cursor = collection.find(query);
82 | System.out.println("( 4."+(p+1)+" ) .find({\"age\" : {\""+or_operators[p]+"\" : [10,20,30]}})");
83 | System.out.println("results --> "+cursor.count());
84 | }
85 | System.out.println("---------------------------------");
86 | //-----------------------------------
87 | // ( 5 ) collection.find({"$or" : [ {"name":"John" },{"age":20}]}) --> get documents by query
88 | BasicDBObject or_conditions[] = {new BasicDBObject("name", "John"),new BasicDBObject("age", 20)};
89 | query = new BasicDBObject("$or", or_conditions);
90 | cursor = collection.find(query);
91 | System.out.println("( 5 ) .find({\"$or\" :[{\"name\":\"John\"},{\"age\":20}]})");
92 | System.out.println("results --> "+cursor.count());
93 | System.out.println("---------------------------------");
94 | //-----------------------------------
95 | // ( 6 ) collection.find({"friends" : ["John","Tim"]},{"name" : 1, "freinds" : 1,"_id":0})) --> get documents by query
96 | String[] friends = {"John","Tim"};
97 | query = new BasicDBObject("friends", new BasicDBObject("$all",friends) );
98 | keys = new BasicDBObject("name", 1).append("friends", 1).append("_id", 0);
99 | cursor = collection.find(query,keys);
100 | System.out.println("( 6 ) .find({\"friends\" : {$all:[\"John\",\"Tim\"]}},{\"name\" : 1, \"freinds\" : 1,\"_id\":0})");
101 | System.out.println("results --> "+cursor.count());
102 | try {
103 | while(cursor.hasNext()) {
104 | System.out.println(cursor.next());
105 | }
106 | } finally {
107 | cursor.close();
108 | }
109 | System.out.println("---------------------------------");
110 | //------------------------------------
111 | // ( 7 ) collection.find({"address" : {"country":"US","state":"NY","city":"Buffalo"}},{"name" : 1, "address" : 1,"_id":0})) --> get documents by query
112 | query = new BasicDBObject("address", new BasicDBObject("country","US").append("state","NY").append("city","Buffalo"));
113 | keys = new BasicDBObject("name", 1).append("address", 1).append("_id", 0);
114 | cursor = collection.find(query,keys);
115 | System.out.println("( 7 ) .find({\"address\" : {\"country\":\"US\",\"state\":\"NY\",\"city\":\"Buffalo\"}},{\"name\" : 1, \"address\" : 1,\"_id\":0})");
116 | System.out.println("results --> "+cursor.count());
117 | try {
118 | while(cursor.hasNext()) {
119 | System.out.println(cursor.next());
120 | }
121 | } finally {
122 | cursor.close();
123 | }
124 | System.out.println("---------------------------------");
125 | //------------------------------------
126 | // ( 8 ) collection.find({"address.state" : "NY"},{"name" : 1, "address" : 1,"_id":0})) --> get documents by query
127 | query = new BasicDBObject("address.state", "NY");
128 | keys = new BasicDBObject("name", 1).append("address", 1).append("_id", 0);
129 | cursor = collection.find(query,keys);
130 | System.out.println("( 8 ) .find({\"address.state\" : \"NY\"},{\"name\" : 1, \"address\" : 1,\"_id\":0})");
131 | System.out.println("results --> "+cursor.count());
132 | try {
133 | while(cursor.hasNext()) {
134 | System.out.println(cursor.next());
135 | }
136 | } finally {
137 | cursor.close();
138 | }
139 | System.out.println("---------------------------------");
140 | /**** Done ****/
141 | System.out.println("Done");
142 |
143 | } catch (UnknownHostException e) {
144 | e.printStackTrace();
145 | } catch (MongoException e) {
146 | e.printStackTrace();
147 | }
148 |
149 | }
150 | }
--------------------------------------------------------------------------------
/mongodb-springdata/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/mongodb-springdata/README.md:
--------------------------------------------------------------------------------
1 | Mogodb Spring Data
2 | ==================
3 |
4 | Building simple mongodb java application using Spring Data.
5 |
--------------------------------------------------------------------------------
/mongodb-springdata/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.hmkcode
6 | mongodb-springdata
7 | 1.0-SNAPSHOT
8 | jar
9 |
10 | mongodb-springdata
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 | org.springframework.data
20 | spring-data-mongodb
21 | 1.1.1.RELEASE
22 |
23 |
24 | commons-logging
25 | commons-logging
26 | 1.1.1
27 | runtime
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/mongodb-springdata/src/main/java/com/hmkcode/spring/data/mongodb/Main.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.spring.data.mongodb;
2 |
3 | import java.util.Collection;
4 | import java.util.LinkedList;
5 | import java.util.List;
6 |
7 | import org.springframework.context.ApplicationContext;
8 | import org.springframework.context.support.ClassPathXmlApplicationContext;
9 | import org.springframework.data.mongodb.core.MongoOperations;
10 | import org.springframework.data.mongodb.core.mapping.Document;
11 | import org.springframework.data.mongodb.core.query.Criteria;
12 | import org.springframework.data.mongodb.core.query.Query;
13 | import org.springframework.data.mongodb.core.query.Update;
14 |
15 | import com.hmkcode.vo.Address;
16 | import com.hmkcode.vo.Person;
17 |
18 | public class Main {
19 |
20 | public static void main(String args[]){
21 |
22 |
23 | ApplicationContext ctx = new ClassPathXmlApplicationContext("com/hmkcode/spring/spring.xml");
24 | MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
25 |
26 | Collection persons = new LinkedList();
27 | persons.add(new Person(2,"Scott"));
28 | persons.add(new Person(3,"Tim"));
29 | persons.add(new Person(4,"Lora"));
30 |
31 |
32 | //( 1 ) save one person
33 | // if collection is not specified in @Document(collection="people"), we need to specify collection name
34 | // in save(document, collection);
35 | mongoOperation.save(new Person(1,"Brit"));
36 | //-------------------------------------------------------
37 |
38 | //( 2 ) insert many persons
39 | //if we have a list of different type of documents to be inserted, their collection will be
40 | //specified by @Document(collection="collectionName")
41 | mongoOperation.insert(persons, Person.class);
42 |
43 | //-------------------------------------------------------
44 | //( 3 ) find inserted person
45 | Person savedPerson = mongoOperation.findOne(
46 | new Query(Criteria.where("name").is("Scott")),
47 | Person.class
48 | );
49 |
50 | System.out.println("saved Person: " + savedPerson);
51 | //-------------------------------------------------------
52 | //( 4 ) find all persons
53 | List allPersons = mongoOperation.findAll(Person.class);
54 |
55 | System.out.println("Number of persons = " + allPersons.size());
56 | //-------------------------------------------------------
57 | //( 5 ) updateMulti
58 | // update
59 | mongoOperation.updateMulti(
60 | new Query(Criteria.where("name").is("Scott")),
61 | Update.update("address", new Address("US","CA","San Diego")),
62 | Person.class
63 | );
64 | //-------------------------------------------------------
65 | //( 6 ) find updated person
66 | Person updatedPerson = mongoOperation.findOne(
67 | new Query(Criteria.where("name").is("Scott")),
68 | Person.class
69 | );
70 |
71 | System.out.println("Updated Person: " + updatedPerson);
72 | //-------------------------------------------------------
73 | //( 7 ) remove person
74 | mongoOperation.remove(new Query(),Person.class);
75 |
76 | System.out.println("Numober persons: " + mongoOperation.findAll(Person.class).size());
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/mongodb-springdata/src/main/java/com/hmkcode/spring/spring.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
22 |
23 |
24 |
25 |
31 |
--------------------------------------------------------------------------------
/mongodb-springdata/src/main/java/com/hmkcode/vo/Address.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.vo;
2 |
3 | public class Address {
4 |
5 | private String country;
6 | private String state;
7 | private String city;
8 |
9 | public Address(String country,String state,String city){
10 | this.country = country;
11 | this.state = state;
12 | this.city = city;
13 | }
14 |
15 | public Address(){}
16 | public String getCountry() {
17 | return country;
18 | }
19 |
20 | public void setCountry(String country) {
21 | this.country = country;
22 | }
23 |
24 | public String getState() {
25 | return state;
26 | }
27 |
28 | public void setState(String state) {
29 | this.state = state;
30 | }
31 |
32 | public String getCity() {
33 | return city;
34 | }
35 |
36 | public void setCity(String city) {
37 | this.city = city;
38 | }
39 |
40 | public String toString(){
41 | return "{country: "+this.country+" , state: "+this.state+" , city: "+this.city+"}";
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/mongodb-springdata/src/main/java/com/hmkcode/vo/Person.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.vo;
2 |
3 | import org.springframework.data.annotation.Id;
4 | import org.springframework.data.mongodb.core.mapping.Document;
5 |
6 | @Document(collection="people")
7 | public class Person {
8 |
9 | //Field annotated with "@Id" or named "id" will be mapped to document _id which is a required field.
10 | //so here we can add @Id or leave it.
11 | @Id
12 | private int id;
13 | private String name;
14 | private String[] friends;
15 | private Address address;
16 |
17 | public Person(int id,String name,String[] friends,Address address){
18 | this.id = id;
19 | this.name = name;
20 | this.friends = friends;
21 | this.address = address;
22 | }
23 |
24 | //instantiate Person with default friends and address
25 | public Person(int id,String name){
26 | this.id = id;
27 | this.name = name;
28 | String f[] = {"John","Brit","Tim"};
29 | this.friends = f;
30 | this.address = new Address("US","NY","New York");
31 | }
32 | public Person(){}
33 |
34 | public int getId() {
35 | return id;
36 | }
37 |
38 | public void setId(int id) {
39 | this.id = id;
40 | }
41 |
42 | public String getName() {
43 | return name;
44 | }
45 |
46 | public void setName(String name) {
47 | this.name = name;
48 | }
49 |
50 | public String[] getFriends() {
51 | return friends;
52 | }
53 |
54 | public void setFriends(String[] friends) {
55 | this.friends = friends;
56 | }
57 |
58 | public Address getAddress() {
59 | return address;
60 | }
61 |
62 | public void setAddress(Address address) {
63 | this.address = address;
64 | }
65 |
66 | public String toString(){
67 | String friendsArray = "";
68 | for(int f = 0 ; f < friends.length;f++)
69 | friendsArray += friends[f]+( (f+1) < friends.length?" , ":"");
70 |
71 | return "{id: "+this.id+", name: "+this.name+", friends: [ "+friendsArray+" ] , address: "+this.address+"}";
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | spring-data-neo4j-person-friends
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.ajdt.core.ajbuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.ajdt.ui.ajnature
16 | org.eclipse.jdt.core.javanature
17 |
18 |
19 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Thu Mar 14 19:10:50 AST 2013
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.6
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.source=1.6
13 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/.shell_history:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hmkcode/nosql/3f41b71e57fdacf14a485d349c1857a861ff24b2/spring-data-neo4j-person-friends/.shell_history
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/README.md:
--------------------------------------------------------------------------------
1 | Spring Data Neo4j
2 | =================
3 |
4 | Simple example showing how to use Spring Data Neo4j.
5 | - It generates a set of 100 persons and connect each of them "create relationships" to exactly 10 other persons from the same set.
6 |
7 | Person.java: simple POJO with needed annotations @NodeEntity, @Indexed, @GraphId...etc
8 | PersonRepository.java: the magic is here! an interface that works without implementation!!
9 |
10 | - Alot of jars are needed pom.xml is not provided yet.
11 | - Running this using eclipse may need some configuration for AspectJ.
12 | Refer to http://hmkcode.com/spring-data-neo4j-ii for more details.
13 |
14 | -HMK
15 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/src/com/hmkcode/FriendMaker.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode;
2 |
3 |
4 |
5 | import java.util.LinkedList;
6 |
7 | public class FriendMaker {
8 |
9 | public static int[][] friendsOf = null;
10 | //This method build unique friends for person
11 | public static int[][] makeFriends(){
12 |
13 | if(friendsOf != null)
14 | return friendsOf;
15 |
16 | friendsOf = new int[100][10];
17 | int randomPersonId;
18 | LinkedList randomFriends;
19 | int f = 0;
20 |
21 | //for each person randomly pick 50 friends
22 | for(int i = 0; i < 100; i++){
23 | System.out.println("Working one.... "+(i+1));
24 |
25 | //pick 50 unique friends add them to linkedList
26 | //LinkedList.contains() will be used to make sure we getting unique friends
27 | randomFriends = new LinkedList();
28 | f = 0;
29 | while(f < 10){
30 | randomPersonId = (int) (Math.random()*100);
31 | if(!randomFriends.contains(randomPersonId+"") && randomPersonId != i && randomPersonId > 0){
32 | randomFriends.add(randomPersonId+"");
33 | f++;
34 | }
35 | }
36 |
37 | //add friends to person i
38 |
39 | for(int x = 0 ; x < 10; x++){
40 | friendsOf[i][x] = Integer.parseInt(randomFriends.get(x));
41 | //System.out.println(i+" - "+x+" = "+friendsOf[i][x]);
42 | //System.out.println("\n------------------------");
43 |
44 | }
45 |
46 | }
47 | return friendsOf;
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/src/com/hmkcode/Main.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode;
2 |
3 |
4 |
5 | import org.springframework.context.ApplicationContext;
6 | import org.springframework.context.support.ClassPathXmlApplicationContext;
7 |
8 | import com.hmkcode.spring.data.neo4j.service.PersonService;
9 |
10 |
11 |
12 |
13 | public class Main{
14 |
15 |
16 | public Main(){
17 | }
18 |
19 |
20 | public static void main(String[] args){
21 | ApplicationContext context = new ClassPathXmlApplicationContext("com/hmkcode/spring/config/spring_aspects.xml");
22 | PersonService personService = (PersonService) context.getBean("personService");
23 | personService.buildDataModel();
24 | System.out.println("Count: "+personService.count());
25 |
26 |
27 | }
28 |
29 |
30 | }
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/src/com/hmkcode/spring/config/spring_aspects.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/src/com/hmkcode/spring/data/neo4j/entity/Person.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.spring.data.neo4j.entity;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | import org.neo4j.graphdb.Direction;
7 | import org.springframework.data.neo4j.annotation.GraphId;
8 | import org.springframework.data.neo4j.annotation.Indexed;
9 | import org.springframework.data.neo4j.annotation.NodeEntity;
10 | import org.springframework.data.neo4j.annotation.RelatedTo;
11 |
12 |
13 | @NodeEntity
14 | public class Person {
15 |
16 |
17 | @Indexed
18 | private String personId;
19 | private String personName;
20 |
21 | @GraphId
22 | private Long nodeId;
23 |
24 | @RelatedTo(type = "FRIEND_OF", direction = Direction.OUTGOING)
25 | private Set friends;
26 |
27 | public Person(String personId, String personName) {
28 | this.personId = personId;
29 | this.personName = personName;
30 | }
31 | public Person(){}
32 | public String getPersonId() {
33 | return personId;
34 | }
35 | public void setPersonId(String personId) {
36 | this.personId = personId;
37 | }
38 | public String getPersonName() {
39 | return personName;
40 | }
41 | public void setPersonName(String personName) {
42 | this.personName = personName;
43 | }
44 | public Long getNodeId() {
45 | return nodeId;
46 | }
47 | public void setNodeId(Long nodeId) {
48 | this.nodeId = nodeId;
49 | }
50 | public Set getFriends() {
51 | return friends;
52 | }
53 | public void setFriends(Set friends) {
54 | this.friends = friends;
55 | }
56 |
57 | public void addFriend(Person friend) {
58 | if(this.friends == null)
59 | this.friends = new HashSet();
60 | this.friends.add(friend);
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/src/com/hmkcode/spring/data/neo4j/repository/PersonRepository.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.spring.data.neo4j.repository;
2 |
3 | import org.springframework.data.neo4j.repository.GraphRepository;
4 |
5 | import com.hmkcode.spring.data.neo4j.entity.Person;;
6 |
7 | public interface PersonRepository extends GraphRepository {}
8 |
--------------------------------------------------------------------------------
/spring-data-neo4j-person-friends/src/com/hmkcode/spring/data/neo4j/service/PersonService.java:
--------------------------------------------------------------------------------
1 | package com.hmkcode.spring.data.neo4j.service;
2 |
3 |
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.hmkcode.FriendMaker;
9 | import com.hmkcode.spring.data.neo4j.entity.Person;
10 | import com.hmkcode.spring.data.neo4j.repository.PersonRepository;
11 |
12 |
13 |
14 | @Service
15 | public class PersonService {
16 |
17 | @Autowired
18 | private PersonRepository personRepository;
19 |
20 | public long count() {
21 |
22 | return personRepository.count();
23 | }
24 |
25 | public Person createPerson(String personId, String personName) {
26 | return personRepository.save(new Person(personId, personName));
27 | }
28 |
29 | public Iterable getAll() {
30 | return personRepository.findAll();
31 | }
32 |
33 | public Person findPersonById(Long id) {
34 | return personRepository.findOne(id);
35 | }
36 |
37 | public Person findWorldByName(String personName) {
38 | return personRepository.findByPropertyValue("personName", personName);
39 | }
40 |
41 |
42 |
43 | public void buildDataModel() {
44 | int[][] friendsOf = FriendMaker.makeFriends();
45 | // create all persons
46 | for(int p = 0; p < 100;p++){
47 | createPerson("id-"+(p+1),"name-"+(p+1)); // id-1, name-1
48 | System.out.println("Created person....."+(p+1));
49 |
50 | }
51 | // add friends
52 | Person person;
53 | for(int p = 0; p < 100;p++){
54 | person = findPersonById(new Long(p+1));
55 | for(int f = 0 ; f < 10; f++){
56 | person.addFriend(findPersonById(new Long(friendsOf[p][f])));
57 | }
58 | System.out.println("Created friends of...."+(p+1));
59 |
60 | personRepository.save(person);
61 | }
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------