├── .gitignore ├── LICENSE ├── README.md ├── build.gradle └── src └── main └── java └── com └── gosololaw └── elasticsearch └── VectorScoringPlugin.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Maven template 3 | target/ 4 | pom.xml.tag 5 | pom.xml.releaseBackup 6 | pom.xml.versionsBackup 7 | pom.xml.next 8 | release.properties 9 | dependency-reduced-pom.xml 10 | buildNumber.properties 11 | .mvn/timing.properties 12 | 13 | ### Gradle 14 | .gradle 15 | 16 | 17 | build/ 18 | 19 | build-idea/ 20 | 21 | # Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) 22 | !/.mvn/wrapper/maven-wrapper.jar 23 | ### Java template 24 | # Compiled class file 25 | *.class 26 | 27 | # Log file 28 | *.log 29 | 30 | # BlueJ files 31 | *.ctxt 32 | 33 | # Mobile Tools for Java (J2ME) 34 | .mtj.tmp/ 35 | 36 | # Package Files # 37 | *.jar 38 | *.war 39 | *.ear 40 | *.zip 41 | *.tar.gz 42 | *.rar 43 | 44 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 45 | hs_err_pid* 46 | ### JetBrains template 47 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 48 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 49 | 50 | # IDE 51 | .idea/ 52 | *.iml 53 | 54 | ## File-based project format: 55 | *.iws 56 | 57 | ## Plugin-specific files: 58 | 59 | # IntelliJ 60 | /out/ 61 | 62 | # JIRA plugin 63 | atlassian-ide-plugin.xml 64 | 65 | # Crashlytics plugin (for Android Studio and IntelliJ) 66 | com_crashlytics_export_strings.xml 67 | crashlytics.properties 68 | crashlytics-build.properties 69 | fabric.properties 70 | 71 | -------------------------------------------------------------------------------- /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, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | You must cause any modified files to carry prominent notices stating that You changed the files; and 37 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 38 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 39 | 40 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 41 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 42 | 43 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 44 | 45 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 46 | 47 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 48 | 49 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fast Elasticsearch Vector Scoring 2 | 3 | This Plugin allows you to score Elasticsearch documents based on embedding-vectors, using dot-product or cosine-similarity. 4 | 5 | ## General 6 | * Updated version for ES 6.1 of [this plugin](https://github.com/lior-k/fast-elasticsearch-vector-scoring) 7 | * Cosine support removed. 8 | * This plugin was inspired from [This elasticsearch vector scoring plugin](https://github.com/MLnick/elasticsearch-vector-scoring) and [this discussion](https://discuss.elastic.co/t/vector-scoring/85227/6) to achieve 10 times faster processing over the original. 9 | * lior-k gained this substantial speed improvement by using the lucene index directly 10 | * lior-k developed it for their workplace which needs to pick KNN from a set of ~4M vectors. Their current ES setup is able to answer this in ~80ms 11 | 12 | 13 | ## Elasticsearch version 14 | * Currently designed for Elasticsearch 6.1.2. 15 | 16 | 17 | ## Setup 18 | 19 | In order to install this plugin, you need to create a zip distribution first by running 20 | 21 | ```bash 22 | gradle clean assemble 23 | ``` 24 | 25 | This will produce a zip file in `build/distributions`. 26 | 27 | After building the zip file, you can install it like this 28 | 29 | ```bash 30 | elasticsearch-plugin install file:///path/to/iplugin/build/distribution/FILENAME.zip 31 | ``` 32 | 33 | 34 | 35 | ## Debugging 36 | Place this into an elasticsearch checkout, add the plugin to the projects list in `/settings.gradle` and run 37 | 38 | gradle :plugins:vector-scoring:run --debug-jvm 39 | 40 | 41 | 42 | ## Usage 43 | 44 | ### Documents 45 | * Each document you score should have a field containing the base64 representation of your vector. for example: 46 | ``` 47 | { 48 | "id": 1, 49 | .... 50 | "content_vector": "v7l48eAAAAA/s4VHwAAAAD+R7I5AAAAAv8MBMAAAAAA/yEI3AAAAAL/IWkeAAAAAv7s480AAAAC/v6DUgAAAAL+wJi0gAAAAP76VqUAAAAC/sL1ZYAAAAL/dyq/gAAAAP62FVcAAAAC/tQRvYAAAAL+j6ycAAAAAP6v1KcAAAAC/bN5hQAAAAL+u9ItAAAAAP4ckTsAAAAC/pmkjYAAAAD+cYpwAAAAAP5renEAAAAC/qY0HQAAAAD+wyYGgAAAAP5WrCcAAAAA/qzjTQAAAAD++LBzAAAAAP49wNKAAAAC/vu/aIAAAAD+hqXfAAAAAP4FfNCAAAAA/pjC64AAAAL+qwT2gAAAAv6S3OGAAAAC/gfMtgAAAAD/If5ZAAAAAP5mcXOAAAAC/xYAU4AAAAL+2nlfAAAAAP7sCXOAAAAA/petBIAAAAD9soYnAAAAAv5R7X+AAAAC/pgM/IAAAAL+ojI/gAAAAP2gPz2AAAAA/3FonoAAAAL/IHg1AAAAAv6p1SmAAAAA/tvKlQAAAAD/I2OMAAAAAP3FBiCAAAAA/wEd8IAAAAL94wI9AAAAAP2Y1IIAAAAA/rnS4wAAAAL9vriVgAAAAv1QxoCAAAAC/1/qu4AAAAL+inZFAAAAAv7aGA+AAAAA/lqYVYAAAAD+kNP0AAAAAP730BiAAAAA=" 51 | } 52 | ``` 53 | * Use this field mapping: 54 | ``` 55 | PUT my_index 56 | { 57 | "mappings": { 58 | "doc": { 59 | "properties": { 60 | "embedding_vector": { 61 | "type": "binary", 62 | "doc_values": true 63 | } 64 | } 65 | } 66 | } 67 | } 68 | ``` 69 | * The vector can be of any dimension 70 | 71 | ### Querying 72 | * For querying the 100 KNN documents use this POST message on your ES index: 73 | 74 | ``` 75 | POST /_search 76 | { 77 | "query": { 78 | "function_score": { 79 | "query": { 80 | "match": { 81 | "name": "Doe" 82 | } 83 | }, 84 | "functions": [ 85 | { 86 | "script_score": { 87 | "script": { 88 | "source": "vector_scoring", 89 | "lang": "binary_vector_score", 90 | "params": { 91 | "vector_field": "content_vector", 92 | "vector": [ 93 | -0.09217305481433868, 94 | 0.010635560378432274, 95 | -0.02878434956073761, 96 | 0.06988169997930527, 97 | 0.1273992955684662, 98 | -0.023723633959889412, 99 | 0.05490724742412567, 100 | -0.12124507874250412, 101 | -0.023694118484854698, 102 | 0.014595639891922474, 103 | 0.1471538096666336, 104 | 0.044936809688806534, 105 | -0.02795785665512085, 106 | -0.05665992572903633, 107 | -0.2441125512123108, 108 | 0.2755320072174072, 109 | 0.11451690644025803, 110 | 0.20242854952812195, 111 | -0.1387604922056198, 112 | 0.05219579488039017, 113 | 0.1145530641078949, 114 | 0.09967200458049774, 115 | 0.2161576747894287, 116 | 0.06157230958342552, 117 | 0.10350126028060913, 118 | 0.20387393236160278, 119 | 0.1367097795009613, 120 | 0.02070528082549572, 121 | 0.19238869845867157, 122 | 0.059613026678562164, 123 | 0.014012521132826805, 124 | 0.16701748967170715, 125 | 0.04985826835036278, 126 | -0.10990987718105316, 127 | -0.12032567709684372, 128 | -0.1450948715209961, 129 | 0.13585780560970306, 130 | 0.037511035799980164, 131 | 0.04251480475068092, 132 | 0.10693439096212387, 133 | -0.08861573040485382, 134 | -0.07457160204648972, 135 | 0.0549330934882164, 136 | 0.19136285781860352, 137 | 0.03346432000398636, 138 | -0.03652812913060188, 139 | -0.1902569830417633, 140 | 0.03250952064990997, 141 | -0.3061246871948242, 142 | 0.05219300463795662, 143 | -0.07879918068647385, 144 | 0.1403723508119583, 145 | -0.08893408626317978, 146 | -0.24330253899097443, 147 | -0.07105310261249542, 148 | -0.18161986768245697, 149 | 0.15501035749912262, 150 | -0.216160386800766, 151 | -0.06377710402011871, 152 | -0.07671763002872467, 153 | 0.05360138416290283, 154 | -0.052845533937215805, 155 | -0.02905619889497757, 156 | 0.08279753476381302 157 | ] 158 | } 159 | } 160 | } 161 | } 162 | ] 163 | } 164 | } 165 | } 166 | ``` 167 | * The example above shows a vector of 64 dimensions 168 | * Parameters: 169 | 1. `field_vector`: The field containing the base64 vector. 170 | 3. `vector`: The vector (comma separated) to compare to. 171 | 172 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elasticsearch under one or more contributor 3 | * license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright 5 | * ownership. Elasticsearch licenses this file to you under 6 | * the Apache License, Version 2.0 (the "License"); you may 7 | * not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | esplugin { 21 | description 'Provides a fast vector multiplication script.' 22 | classname 'com.gosololaw.elasticsearch.VectorScoringPlugin' 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/gosololaw/elasticsearch/VectorScoringPlugin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed under the Apache License, Version 2.0 (the "License"); 3 | * you may not use this file except in compliance with the License. 4 | * You may obtain a copy of the License at 5 | * 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | package com.gosololaw.elasticsearch; 15 | 16 | import org.apache.lucene.index.*; 17 | 18 | import org.apache.lucene.store.ByteArrayDataInput; 19 | import org.elasticsearch.common.settings.Settings; 20 | import org.elasticsearch.plugins.Plugin; 21 | import org.elasticsearch.plugins.ScriptPlugin; 22 | import org.elasticsearch.script.ScriptContext; 23 | import org.elasticsearch.script.ScriptEngine; 24 | import org.elasticsearch.script.SearchScript; 25 | import org.elasticsearch.search.lookup.LeafSearchLookup; 26 | 27 | import java.nio.ByteBuffer; 28 | import java.nio.DoubleBuffer; 29 | import java.io.IOException; 30 | import java.util.ArrayList; 31 | import java.util.Collection; 32 | import java.util.Map; 33 | 34 | /** 35 | * This class is instantiated when Elasticsearch loads the plugin for the 36 | * first time. If you change the name of this plugin, make sure to update 37 | * src/main/resources/es-plugin.properties file that points to this class. 38 | */ 39 | public final class VectorScoringPlugin extends Plugin implements ScriptPlugin { 40 | 41 | private static final int DOUBLE_SIZE = 8; 42 | 43 | @Override 44 | public ScriptEngine getScriptEngine(Settings settings, Collection> contexts) { 45 | return new VectorScoreEngine(); 46 | } 47 | 48 | /** An example {@link ScriptEngine} that uses Lucene segment details to implement pure document frequency scoring. */ 49 | // tag::expert_engine 50 | private static class VectorScoreEngine implements ScriptEngine { 51 | 52 | @Override 53 | public String getType() { 54 | return "binary_vector_score"; 55 | } 56 | 57 | @Override 58 | @SuppressWarnings("unchecked") 59 | public T compile(String scriptName, String scriptSource, ScriptContext context, Map params) { 60 | if (!context.equals(SearchScript.CONTEXT)) { 61 | throw new IllegalArgumentException(getType() + " scripts cannot be used for context [" + context.name + "]"); 62 | } 63 | // we use the script "source" as the script identifier 64 | if ("vector_scoring".equals(scriptSource)) { 65 | SearchScript.Factory factory = (p, lookup) -> new SearchScript.LeafFactory() { 66 | private final double[] inputVector; 67 | final String field; 68 | { 69 | final Object field = p.get("vector_field"); 70 | if (field == null) 71 | throw new IllegalArgumentException("binary_vector_score script requires field vector_field"); 72 | this.field = field.toString(); 73 | 74 | // get query inputVector - convert to primitive 75 | final ArrayList tmp = (ArrayList) p.get("vector"); 76 | this.inputVector = new double[tmp.size()]; 77 | for (int i = 0; i < inputVector.length; i++) { 78 | inputVector[i] = tmp.get(i); 79 | } 80 | } 81 | 82 | @Override 83 | public SearchScript newInstance(LeafReaderContext context) throws IOException { 84 | 85 | return new SearchScript(p, lookup, context) { 86 | BinaryDocValues accessor = context.reader().getBinaryDocValues(field); 87 | Boolean is_value = false; 88 | 89 | @Override 90 | public void setDocument(int docId) { 91 | try { 92 | accessor.advanceExact(docId); 93 | is_value = true; 94 | } catch (IOException e) { 95 | is_value = false; 96 | } 97 | } 98 | 99 | @Override 100 | public double runAsDouble() { 101 | if (!is_value) return 0; 102 | final byte[] bytes; 103 | try { 104 | bytes = accessor.binaryValue().bytes; 105 | } catch (IOException e) { 106 | return 0; 107 | } 108 | 109 | final int input_vector_size = inputVector.length; 110 | 111 | final ByteArrayDataInput doc_vector = new ByteArrayDataInput(bytes); 112 | doc_vector.readVInt(); // returns the number of values which should be 1, MUST appear hear since it affect the next calls 113 | final int doc_vector_length = doc_vector.readVInt(); // returns the number of bytes to read 114 | if(doc_vector_length != input_vector_size * DOUBLE_SIZE) { 115 | return 0.0; 116 | } 117 | final int position = doc_vector.getPosition(); 118 | final DoubleBuffer doubleBuffer = ByteBuffer.wrap(bytes, position, doc_vector_length).asDoubleBuffer(); 119 | 120 | final double[] docVector = new double[input_vector_size]; 121 | doubleBuffer.get(docVector); 122 | 123 | double score = 0; 124 | for (int i = 0; i < input_vector_size; i++) { 125 | score += docVector[i] * inputVector[i]; 126 | } 127 | return score; 128 | } 129 | }; 130 | } 131 | 132 | @Override 133 | public boolean needs_score() { 134 | return false; 135 | } 136 | }; 137 | return context.factoryClazz.cast(factory); 138 | } 139 | throw new IllegalArgumentException("Unknown script name " + scriptSource); 140 | } 141 | 142 | @Override 143 | public void close() { 144 | // optionally close resources 145 | } 146 | 147 | } 148 | // end::expert_engine 149 | 150 | } --------------------------------------------------------------------------------