├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src └── main ├── assembly └── assembly.xml ├── java └── com │ └── orientechnologies │ └── es │ ├── command │ └── OServerCommandESSync.java │ └── plugin │ └── es │ ├── OElasticSearchDatabaseConfiguration.java │ ├── OElasticSearchDatabaseSync.java │ └── OElasticSearchPlugin.java └── resources ├── elastic-search-config.json └── plugin.json /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | target/ 3 | *.iml 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Installation 2 | 3 | This is the manual procedure to install Elastic Search plugin in OrientDB. 4 | 5 | ### 1. Compiles the plugin 6 | 7 | `mvn clean install` 8 | 9 | ### 2. Copy libraries under OrientDB's `lib` directory. 10 | 11 | Copy the generated `orientdb-elasticsearch-*-dist.jar` file is under the target directory into OrientDB lib directory. 12 | 13 | ### 3. Register the OrientDB Elastic Search plugin 14 | 15 | In OrientDB's `config/orientdb-config.xml` file under the `handlers` (Handler is a plugin) tag, add this XML snippet: 16 | 17 | ```xml 18 | 19 | 20 | 21 | 22 | 23 | ``` 24 | 25 | ### 4. Configure the synchronization 26 | 27 | The Elastic Search plugin creates this file under `databases//elastic-search-config.json`: 28 | 29 | ```json 30 | { 31 | "es": { 32 | "host": "localhost", 33 | "port": 9220, 34 | "clusterName": "elasticsearch" 35 | }, 36 | "include": { 37 | "classes": { 38 | }, 39 | "clusters": { 40 | } 41 | }, 42 | "exclude": { 43 | "classes": [], 44 | "clusters": [] 45 | } 46 | } 47 | ``` 48 | 49 | You can modify it to configure the synchronization. 50 | 51 | ### 5. Execute a synchronization 52 | 53 | You can execute a synchronization of classes, clusters or even the output of a command: 54 | - classes 55 | - clusters 56 | - command 57 | 58 | Example synchronizing the class "V": 59 | ``` 60 | curl -u admin:admin --data "{'classes':['V']}" http://localhost:2480/essync/GamesOfThrones 61 | {"result":[{"@type":"d","@version":0,"value":"Synchronized 2261 records"}]} 62 | ``` 63 | 64 | Example synchronizing a query: 65 | ``` 66 | curl -u admin:admin --data "{'command':'select from V where age > 10'}" http://localhost:2480/essync/GamesOfThrones 67 | {"result":[{"@type":"d","@version":0,"value":"Synchronized 23 records"}]} 68 | ``` 69 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 18 | 19 | 21 | 4.0.0 22 | 23 | com.orientechnologies 24 | orientdb-elasticsearch 25 | 2.2.9-SNAPSHOT 26 | jar 27 | 28 | 29 | 1.6 30 | 1.7 31 | ${version} 32 | 2.1.2 33 | UTF-8 34 | UTF-8 35 | UTF-8 36 | 1.6 37 | 1.6 38 | yyyy-MM-dd HH:mm:ssZ 39 | 40 | 41 | OrientDB Elastic Search connector 42 | OrientDB Connector to Elastic Search 43 | http://maven.apache.org 44 | 2016 45 | 46 | 47 | 48 | 49 | org.apache.maven.plugins 50 | maven-shade-plugin 51 | 2.4.1 52 | 53 | ${basedir}/target/dependency-reduced-pom.xml 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | org.apache.lucene:* 65 | 66 | 67 | 68 | 69 | org.apache.lucene 70 | com.orientechnologies.elasticsearch.lucene 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | maven-assembly-plugin 79 | 80 | 81 | src/main/assembly/assembly.xml 82 | 83 | 84 | 85 | 86 | make-assembly 87 | package 88 | 89 | single 90 | 91 | 92 | 93 | 94 | 95 | 96 | org.apache.maven.plugins 97 | maven-compiler-plugin 98 | 99 | 1.6 100 | 1.7 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | com.orientechnologies 109 | orientdb-core 110 | ${orientdb.version} 111 | provided 112 | 113 | 114 | com.orientechnologies 115 | orientdb-server 116 | ${orientdb.version} 117 | provided 118 | 119 | 120 | com.orientechnologies 121 | orientdb-tools 122 | ${orientdb.version} 123 | provided 124 | 125 | 126 | org.elasticsearch 127 | elasticsearch 128 | ${es.version} 129 | 130 | 131 | org.apache.lucene 132 | * 133 | 134 | 135 | 136 | 137 | 138 | 139 | com.google.guava 140 | guava 141 | 18.0 142 | runtime 143 | 144 | 145 | com.carrotsearch 146 | hppc 147 | 0.7.1 148 | 149 | 150 | 151 | 152 | 153 | sonatype-nexus-staging 154 | OrientDB Maven2 Repository 155 | https://oss.sonatype.org/service/local/staging/deploy/maven2 156 | 157 | 158 | sonatype-nexus-snapshots 159 | OrientDB Maven2 Snapshot Repository 160 | https://oss.sonatype.org/content/repositories/snapshots 161 | false 162 | 163 | 164 | 165 | 166 | sonatype-nexus-snapshots 167 | Sonatype Nexus Snapshots 168 | https://oss.sonatype.org/content/repositories/snapshots 169 | 170 | false 171 | 172 | 173 | true 174 | 175 | 176 | 177 | maven2-repository.dev.java.net 178 | Java.net repository 179 | http://download.java.net/maven/2 180 | 181 | 182 | osgeo 183 | Open Source Geospatial Foundation Repository 184 | http://download.osgeo.org/webdav/geotools/ 185 | 186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /src/main/assembly/assembly.xml: -------------------------------------------------------------------------------- 1 | 2 | dist 3 | 4 | jar 5 | 6 | false 7 | 8 | 9 | 10 | true 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/main/java/com/orientechnologies/es/command/OServerCommandESSync.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 OrientDB LTD (info(at)orientdb.com) 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * * 17 | * * For more information: http://www.orientdb.com 18 | * 19 | */ 20 | package com.orientechnologies.es.command; 21 | 22 | import com.orientechnologies.common.collection.OIterableObject; 23 | import com.orientechnologies.common.log.OLogManager; 24 | import com.orientechnologies.es.plugin.es.OElasticSearchPlugin; 25 | import com.orientechnologies.orient.core.command.OCommandExecutor; 26 | import com.orientechnologies.orient.core.command.OCommandManager; 27 | import com.orientechnologies.orient.core.command.OCommandRequestText; 28 | import com.orientechnologies.orient.core.db.document.ODatabaseDocument; 29 | import com.orientechnologies.orient.core.db.record.OIdentifiable; 30 | import com.orientechnologies.orient.core.record.impl.ODocument; 31 | import com.orientechnologies.orient.server.network.protocol.http.OHttpRequest; 32 | import com.orientechnologies.orient.server.network.protocol.http.OHttpResponse; 33 | import com.orientechnologies.orient.server.network.protocol.http.command.OServerCommandAuthenticatedDbAbstract; 34 | 35 | import java.util.ArrayList; 36 | import java.util.Collection; 37 | import java.util.List; 38 | 39 | public class OServerCommandESSync extends OServerCommandAuthenticatedDbAbstract { 40 | private static final String[] NAMES = { "GET|essync/*", "POST|essync/*" }; 41 | 42 | private final OElasticSearchPlugin es; 43 | 44 | public OServerCommandESSync(final OElasticSearchPlugin es) { 45 | this.es = es; 46 | } 47 | 48 | @Override 49 | public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception { 50 | 51 | OLogManager.instance().info(this, "ES sync commmand received"); 52 | final String[] urlParts = checkSyntax(iRequest.url, 1, "Syntax error: essync/"); 53 | 54 | String command = null; 55 | List classes = null; 56 | List clusters = null; 57 | 58 | if (iRequest.content != null && !iRequest.content.isEmpty()) { 59 | // CONTENT REPLACES TEXT 60 | if (iRequest.content.startsWith("{")) { 61 | // JSON PAYLOAD 62 | final ODocument doc = new ODocument().fromJSON(iRequest.content); 63 | command = doc.field("command"); 64 | clusters = doc.field("clusters"); 65 | classes = doc.field("classes"); 66 | } 67 | } 68 | 69 | iRequest.data.commandInfo = "Elastic Search Sync"; 70 | iRequest.data.commandDetail = command != null ? 71 | "command: " + command : 72 | classes != null ? "classes: " + classes.toString() : clusters != null ? "clusters: " + clusters.toString() : "database"; 73 | 74 | ODatabaseDocument db = null; 75 | 76 | Object response; 77 | 78 | try { 79 | db = getProfiledDatabaseInstance(iRequest); 80 | 81 | long syncItems = 0; 82 | 83 | OLogManager.instance().info(this, "ES plugin: synchronizing records", syncItems); 84 | 85 | if (command != null) { 86 | // COMMAND 87 | final OCommandRequestText cmd = (OCommandRequestText) OCommandManager.instance().getRequester("sql"); 88 | cmd.setText(command); 89 | 90 | final OCommandExecutor executor = OCommandManager.instance().getExecutor(cmd); 91 | executor.setContext(cmd.getContext()); 92 | executor.setProgressListener(cmd.getProgressListener()); 93 | executor.parse(cmd); 94 | 95 | final Object result = db.command(cmd).execute(); 96 | 97 | if (result instanceof OIdentifiable) 98 | syncItems += es.getDatabase(db.getName()).syncBatch(new OIterableObject((OIdentifiable) result)); 99 | else if (result instanceof Collection) 100 | syncItems += es.getDatabase(db.getName()).syncBatch(((Collection) result).iterator()); 101 | else 102 | throw new IllegalArgumentException("The result of command '" + cmd + "' cannot be synchronized"); 103 | 104 | } else if (classes != null) { 105 | // CLASSES 106 | for (String cl : classes) { 107 | syncItems += es.getDatabase(db.getName()).syncBatch(db.browseClass(cl)); 108 | } 109 | 110 | } else if (clusters != null) { 111 | // CLUSTERS 112 | for (String cl : clusters) { 113 | syncItems += es.getDatabase(db.getName()).syncBatch(db.browseCluster(cl)); 114 | } 115 | } else { 116 | // ENTIRE DATABASE BASED ON CFG 117 | clusters = new ArrayList(db.getClusterNames()); 118 | for (String cl : clusters) { 119 | syncItems += es.getDatabase(db.getName()).syncBatch(db.browseCluster(cl)); 120 | } 121 | } 122 | 123 | OLogManager.instance().info(this, "ES plugin: synchronized %d records", syncItems); 124 | 125 | iResponse.writeResult("Synchronized " + syncItems + " records", null, null); 126 | 127 | } finally { 128 | if (db != null) 129 | db.close(); 130 | } 131 | 132 | return false; 133 | } 134 | 135 | @Override 136 | public String[] getNames() { 137 | return NAMES; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/com/orientechnologies/es/plugin/es/OElasticSearchDatabaseConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 OrientDB LTD (info(at)orientdb.com) 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * * 17 | * * For more information: http://www.orientdb.com 18 | * 19 | */ 20 | package com.orientechnologies.es.plugin.es; 21 | 22 | import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; 23 | import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; 24 | import com.orientechnologies.orient.core.record.impl.ODocument; 25 | import org.elasticsearch.client.Client; 26 | 27 | import java.util.Collection; 28 | import java.util.Collections; 29 | import java.util.HashMap; 30 | import java.util.HashSet; 31 | import java.util.Map; 32 | import java.util.Set; 33 | 34 | /** 35 | * Elastic Search database configuration. 36 | * 37 | * @author Luca Garulli 38 | */ 39 | public class OElasticSearchDatabaseConfiguration { 40 | private final Map> includeClasses = new HashMap>(); 41 | private final Map> includeClusters = new HashMap>(); 42 | private final Set excludeClasses = new HashSet(); 43 | private final Set excludeClusters = new HashSet(); 44 | private final Client client; 45 | 46 | public OElasticSearchDatabaseConfiguration(final Client client, final ODocument configuration) { 47 | this.client = client; 48 | 49 | if (configuration.eval("exclude.classes") != null) 50 | excludeClasses.addAll((Collection) configuration.eval("exclude.classes")); 51 | 52 | if (configuration.eval("exclude.clusters") != null) 53 | excludeClusters.addAll((Collection) configuration.eval("exclude.clusters")); 54 | 55 | if (configuration.eval("include.clusters") != null) { 56 | final ODocument incClusters = (ODocument) configuration.eval("include.clusters"); 57 | for (String cl : incClusters.fieldNames()) { 58 | final Collection clFields = incClusters.field(cl); 59 | if (clFields != null) 60 | includeClusters.put(cl, new HashSet(clFields)); 61 | else 62 | includeClusters.put(cl, new HashSet()); 63 | } 64 | } 65 | 66 | if (configuration.eval("include.classes") != null) { 67 | final ODocument incClasses = (ODocument) configuration.eval("include.classes"); 68 | for (String cl : incClasses.fieldNames()) { 69 | final Collection clFields = incClasses.field(cl); 70 | if (clFields != null) 71 | includeClasses.put(cl, new HashSet(clFields)); 72 | else 73 | includeClasses.put(cl, new HashSet()); 74 | } 75 | } 76 | } 77 | 78 | /** 79 | * Returns null if the record must be not synchronized, other wise the set of fields to synchronize. An empty set means all the 80 | * fields. 81 | */ 82 | public Set getSyncFields(final ODocument record) { 83 | final String className = record.getClassName(); 84 | if (className == null) 85 | return null; 86 | 87 | if (excludeClasses.contains(className)) 88 | return null; 89 | 90 | final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.get(); 91 | 92 | final String clusterName = db.getClusterNameById(record.getIdentity().getClusterId()); 93 | if (excludeClasses.contains(clusterName)) 94 | return null; 95 | 96 | if (!includeClasses.isEmpty()) { 97 | if (includeClasses.containsKey(className)) 98 | return includeClasses.get(className); 99 | } 100 | 101 | if (!includeClusters.isEmpty()) { 102 | if (includeClusters.containsKey(clusterName)) 103 | return includeClusters.get(clusterName); 104 | } 105 | 106 | // SYNCHRONIZE ALL FIELDS 107 | return Collections.EMPTY_SET; 108 | } 109 | 110 | public Client getClient() { 111 | return client; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/orientechnologies/es/plugin/es/OElasticSearchDatabaseSync.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 OrientDB LTD (info(at)orientdb.com) 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * * 17 | * * For more information: http://www.orientdb.com 18 | * 19 | */ 20 | package com.orientechnologies.es.plugin.es; 21 | 22 | import com.orientechnologies.orient.core.db.record.OIdentifiable; 23 | import com.orientechnologies.orient.core.db.record.ridbag.ORidBag; 24 | import com.orientechnologies.orient.core.hook.ODocumentHookAbstract; 25 | import com.orientechnologies.orient.core.record.ORecord; 26 | import com.orientechnologies.orient.core.record.impl.ODocument; 27 | import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; 28 | import org.elasticsearch.action.bulk.BulkProcessor; 29 | import org.elasticsearch.action.bulk.BulkRequest; 30 | import org.elasticsearch.action.bulk.BulkRequestBuilder; 31 | import org.elasticsearch.action.bulk.BulkResponse; 32 | import org.elasticsearch.action.delete.DeleteRequest; 33 | import org.elasticsearch.action.index.IndexRequest; 34 | import org.elasticsearch.action.search.SearchResponse; 35 | import org.elasticsearch.action.search.SearchType; 36 | import org.elasticsearch.common.unit.ByteSizeUnit; 37 | import org.elasticsearch.common.unit.ByteSizeValue; 38 | import org.elasticsearch.common.unit.TimeValue; 39 | import org.elasticsearch.index.query.QueryBuilders; 40 | import org.elasticsearch.search.SearchHit; 41 | 42 | import java.util.ArrayList; 43 | import java.util.HashMap; 44 | import java.util.Iterator; 45 | import java.util.List; 46 | import java.util.Map; 47 | import java.util.Set; 48 | 49 | /** 50 | * Elastic Search connector plugin. 51 | * 52 | * @author Luca Garulli 53 | */ 54 | public class OElasticSearchDatabaseSync extends ODocumentHookAbstract { 55 | 56 | private final OElasticSearchDatabaseConfiguration esClient; 57 | private final String dbName; 58 | 59 | public OElasticSearchDatabaseSync(final String dbName, final OElasticSearchDatabaseConfiguration esClient) { 60 | this.dbName = dbName; 61 | this.esClient = esClient; 62 | } 63 | 64 | public long syncBatch(final Iterator iterator) { 65 | final BulkProcessor bulkProcessor = BulkProcessor.builder(esClient.getClient(), new BulkProcessor.Listener() { 66 | 67 | @Override 68 | public void beforeBulk(long l, BulkRequest bulkRequest) { 69 | } 70 | 71 | @Override 72 | public void afterBulk(long l, BulkRequest bulkRequest, BulkResponse bulkResponse) { 73 | } 74 | 75 | @Override 76 | public void afterBulk(long l, BulkRequest bulkRequest, Throwable throwable) { 77 | } 78 | }).setBulkActions(10000).setBulkSize(new ByteSizeValue(10, ByteSizeUnit.MB)).setFlushInterval(TimeValue.timeValueSeconds(30)) 79 | .build(); 80 | 81 | long syncItems; 82 | for (syncItems = 0; iterator.hasNext(); syncItems++) { 83 | final OIdentifiable id = iterator.next(); 84 | 85 | final ORecord record = id.getRecord(); 86 | 87 | final Map map = getMap(record); 88 | 89 | if (map != null) 90 | bulkProcessor.add( 91 | new IndexRequest(getIndexName(), ((ODocument) record).getClassName(), record.getIdentity().toString()).source(map)); 92 | } 93 | 94 | bulkProcessor.close(); 95 | 96 | return syncItems; 97 | } 98 | 99 | protected Map getMap(final ORecord record) { 100 | Map map = null; 101 | 102 | if (record instanceof ODocument) { 103 | final ODocument doc = (ODocument) record; 104 | 105 | final Set syncFields = esClient.getSyncFields(doc); 106 | if (syncFields == null) 107 | return null; 108 | 109 | map = new HashMap(); 110 | 111 | map.put("@rid", doc.getIdentity()); 112 | map.put("@class", doc.getClassName()); 113 | 114 | for (String f : doc.fieldNames()) { 115 | if (!syncFields.isEmpty() && !syncFields.contains(f)) 116 | // SKIP FIELD 117 | continue; 118 | 119 | final Object value = doc.field(f); 120 | 121 | if (value instanceof ORidBag) { 122 | final List list = new ArrayList(); 123 | for (Iterator it = ((ORidBag) value).rawIterator(); it.hasNext(); ) { 124 | list.add(it.next()); 125 | } 126 | map.put(f, list); 127 | 128 | } else if (value instanceof ORecord && ((ORecord) value).getIdentity().isPersistent()) { 129 | map.put(f, ((ORecord) value).getIdentity()); 130 | } else 131 | map.put(f, value); 132 | } 133 | } 134 | 135 | return map; 136 | } 137 | 138 | @Override 139 | public void onRecordAfterCreate(final ODocument iDocument) { 140 | esClient.getClient().prepareIndex(getIndexName(), iDocument.getClassName(), iDocument.getIdentity().toString()) 141 | .setSource(iDocument.toMap()).get(); 142 | } 143 | 144 | @Override 145 | public void onRecordAfterUpdate(ODocument iDocument) { 146 | esClient.getClient().prepareIndex(getIndexName(), iDocument.getClassName(), iDocument.getIdentity().toString()) 147 | .setSource(iDocument.toMap()).get(); 148 | } 149 | 150 | @Override 151 | public void onRecordAfterDelete(ODocument iDocument) { 152 | esClient.getClient().delete(new DeleteRequest(getIndexName(), iDocument.getClassName(), iDocument.getIdentity().toString())); 153 | } 154 | 155 | @Override 156 | public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() { 157 | return DISTRIBUTED_EXECUTION_MODE.BOTH; 158 | } 159 | 160 | protected String getIndexName() { 161 | return dbName.toLowerCase(); 162 | } 163 | 164 | public void dropClass(final String className) { 165 | SearchResponse scrollResponse = esClient.getClient().prepareSearch(getIndexName()).setTypes(className) 166 | .setSearchType(SearchType.SCAN).setScroll(new TimeValue(60000)).setQuery(QueryBuilders.matchAllQuery()).setSize(100).get(); 167 | final BulkRequestBuilder bulkRequestBuilder = esClient.getClient().prepareBulk().setRefresh(true); 168 | while (true) { 169 | if (scrollResponse.getHits().getHits().length == 0) { 170 | break; 171 | } 172 | 173 | for (SearchHit hit : scrollResponse.getHits().getHits()) { 174 | bulkRequestBuilder.add(esClient.getClient().prepareDelete(getIndexName(), className, hit.getId())); 175 | } 176 | 177 | scrollResponse = esClient.getClient().prepareSearchScroll(scrollResponse.getScrollId()).setScroll(new TimeValue(60000)).get(); 178 | } 179 | if (bulkRequestBuilder.numberOfActions() > 0) { 180 | bulkRequestBuilder.get(); 181 | } 182 | } 183 | 184 | public void drop() { 185 | esClient.getClient().admin().indices().delete(new DeleteIndexRequest(getIndexName())).actionGet(); 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/main/java/com/orientechnologies/es/plugin/es/OElasticSearchPlugin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 OrientDB LTD (info(at)orientdb.com) 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * * 17 | * * For more information: http://www.orientdb.com 18 | * 19 | */ 20 | package com.orientechnologies.es.plugin.es; 21 | 22 | import com.orientechnologies.common.io.OIOUtils; 23 | import com.orientechnologies.common.log.OLogManager; 24 | import com.orientechnologies.es.command.OServerCommandESSync; 25 | import com.orientechnologies.orient.core.Orient; 26 | import com.orientechnologies.orient.core.db.ODatabaseInternal; 27 | import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener; 28 | import com.orientechnologies.orient.core.exception.OConfigurationException; 29 | import com.orientechnologies.orient.core.metadata.schema.OClass; 30 | import com.orientechnologies.orient.core.record.impl.ODocument; 31 | import com.orientechnologies.orient.server.OServer; 32 | import com.orientechnologies.orient.server.config.OServerParameterConfiguration; 33 | import com.orientechnologies.orient.server.network.OServerNetworkListener; 34 | import com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpAbstract; 35 | import com.orientechnologies.orient.server.plugin.OServerPluginAbstract; 36 | import org.elasticsearch.client.transport.TransportClient; 37 | import org.elasticsearch.common.settings.Settings; 38 | import org.elasticsearch.common.transport.InetSocketTransportAddress; 39 | 40 | import java.io.File; 41 | import java.io.IOException; 42 | import java.net.InetAddress; 43 | import java.net.UnknownHostException; 44 | import java.util.concurrent.ConcurrentHashMap; 45 | 46 | /** 47 | * Elastic Search connector plugin. 48 | */ 49 | public class OElasticSearchPlugin extends OServerPluginAbstract implements ODatabaseLifecycleListener { 50 | private OServer server; 51 | private ConcurrentHashMap clientConfigurations = new ConcurrentHashMap(); 52 | 53 | private boolean enabled = false; 54 | 55 | @Override 56 | public void config(final OServer server, final OServerParameterConfiguration[] iParams) { 57 | this.server = server; 58 | 59 | for (OServerParameterConfiguration param : iParams) { 60 | if (param.name.equalsIgnoreCase("enabled")) { 61 | if (Boolean.parseBoolean(param.value)) 62 | // ENABLE IT 63 | 64 | enabled = true; 65 | } 66 | } 67 | OLogManager.instance().info(this, "Elastic sync plugin enabled:: " + enabled); 68 | } 69 | 70 | @Override 71 | public void startup() { 72 | if (!enabled) 73 | return; 74 | 75 | Orient.instance().addDbLifecycleListener(this); 76 | 77 | final OServerNetworkListener listener = server.getListenerByProtocol(ONetworkProtocolHttpAbstract.class); 78 | if (listener == null) 79 | throw new OConfigurationException("HTTP listener not found"); 80 | 81 | listener.registerStatelessCommand(new OServerCommandESSync(this)); 82 | } 83 | 84 | @Override 85 | public void shutdown() { 86 | if (clientConfigurations != null) { 87 | for (OElasticSearchDatabaseConfiguration c : clientConfigurations.values()) 88 | c.getClient().close(); 89 | 90 | clientConfigurations.clear(); 91 | } 92 | } 93 | 94 | @Override 95 | public PRIORITY getPriority() { 96 | return PRIORITY.LAST; 97 | } 98 | 99 | @Override 100 | public void onCreate(final ODatabaseInternal iDatabase) { 101 | onOpen(iDatabase); 102 | } 103 | 104 | @Override 105 | public void onOpen(final ODatabaseInternal iDatabase) { 106 | 107 | if (iDatabase.getName().equalsIgnoreCase("OSystem")) 108 | return; 109 | 110 | OLogManager.instance().info(this, "loading ES conf for database %s", iDatabase.getName()); 111 | final OElasticSearchDatabaseSync db = new OElasticSearchDatabaseSync(iDatabase.getName(), getESClient(iDatabase.getName())); 112 | iDatabase.registerHook(db); 113 | } 114 | 115 | @Override 116 | public void onClose(final ODatabaseInternal iDatabase) { 117 | } 118 | 119 | @Override 120 | public void onDrop(final ODatabaseInternal iDatabase) { 121 | getDatabase(iDatabase.getName()).drop(); 122 | } 123 | 124 | @Override 125 | public void onCreateClass(final ODatabaseInternal iDatabase, final OClass iClass) { 126 | } 127 | 128 | @Override 129 | public void onDropClass(final ODatabaseInternal iDatabase, final OClass iClass) { 130 | getDatabase(iDatabase.getName()).dropClass(iClass.getName()); 131 | } 132 | 133 | @Override 134 | public void onLocalNodeConfigurationRequest(final ODocument iConfiguration) { 135 | } 136 | 137 | public OElasticSearchDatabaseConfiguration getESClient(final String dbName) { 138 | OElasticSearchDatabaseConfiguration clientCfg = clientConfigurations.get(dbName); 139 | 140 | if (clientCfg == null) { 141 | final ODocument configuration = new ODocument(); 142 | 143 | final File esConfig = new File(server.getDatabaseDirectory() + dbName + "/elastic-search-config.json"); 144 | if (esConfig.exists()) { 145 | try { 146 | configuration.fromJSON(OIOUtils.readFileAsString(esConfig), "noMap"); 147 | } catch (IOException e) { 148 | OLogManager.instance().error(this, "Error on loading JSON file: %s", e, esConfig); 149 | } 150 | } else { 151 | OLogManager.instance().warn(this, "Database %s is not configured for sync on ES", dbName); 152 | 153 | return clientCfg; 154 | } 155 | 156 | try { 157 | String esClusterName = "elasticsearch"; 158 | String esServer = "localhost"; 159 | int esPort = 9300; 160 | 161 | if (configuration.containsField("es")) { 162 | // READ SETTING FROM CONFIGURATION 163 | esServer = (String) configuration.eval("es.host"); 164 | esPort = (Integer) configuration.eval("es.port"); 165 | esClusterName = (String) configuration.eval("es.clusterName"); 166 | } 167 | 168 | final Settings settings = Settings.settingsBuilder().put("cluster.name", esClusterName).build(); 169 | clientCfg = new OElasticSearchDatabaseConfiguration(TransportClient.builder().settings(settings).build() 170 | .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esServer), esPort)), configuration); 171 | 172 | final OElasticSearchDatabaseConfiguration existentClient = clientConfigurations.putIfAbsent(dbName, clientCfg); 173 | if (existentClient != null) { 174 | // CONCURRENT INSERT: CLOSE CURRENT ONE AND USE THE EXISTENT 175 | clientCfg.getClient().close(); 176 | clientCfg = existentClient; 177 | } 178 | } catch (UnknownHostException e) { 179 | 180 | OLogManager.instance().error(this, "Error on connecting to ES server", e); 181 | } 182 | 183 | } 184 | 185 | return clientCfg; 186 | } 187 | 188 | public OElasticSearchDatabaseSync getDatabase(final String dbName) { 189 | return new OElasticSearchDatabaseSync(dbName, getESClient(dbName)); 190 | } 191 | 192 | @Override 193 | public String getName() { 194 | return "es-plugin"; 195 | } 196 | 197 | } 198 | -------------------------------------------------------------------------------- /src/main/resources/elastic-search-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "es": { 3 | "host": "localhost", 4 | "port": 9300, 5 | "clusterName": "elasticsearch" 6 | }, 7 | "include": { 8 | "classes": { 9 | }, 10 | "clusters": { 11 | } 12 | }, 13 | "exclude": { 14 | "classes": [], 15 | "clusters": [] 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/resources/plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "es", 3 | "version": "2.2", 4 | "javaClass": "com.orientechnologies.es.plugin.es.OElasticSearchPlugin", 5 | "parameters": {}, 6 | "description": "This is the OrientDB Elastic Search Connector Plugin", 7 | "web": "http://www.orientdb.com", 8 | "copyrights": "OrientDB LTD", 9 | "license": "Commercial" 10 | } 11 | --------------------------------------------------------------------------------