├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── assemblies │ └── plugin.xml ├── java │ └── com │ │ └── liorkn │ │ └── elasticsearch │ │ ├── Util.java │ │ ├── plugin │ │ └── VectorScoringPlugin.java │ │ ├── script │ │ └── VectorScoreScript.java │ │ └── service │ │ └── VectorScoringScriptEngineService.java └── resources │ ├── license-check │ ├── license_header_definition.xml │ └── vector_scoring_license_header.txt │ └── plugin-descriptor.properties └── test └── java └── com └── liorkn └── elasticsearch ├── EmbeddedElasticsearchServer.java ├── NodeExt.java ├── PluginTest.java └── TestObject.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 | # Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) 14 | !/.mvn/wrapper/maven-wrapper.jar 15 | ### Java template 16 | # Compiled class file 17 | *.class 18 | 19 | # Log file 20 | *.log 21 | 22 | # BlueJ files 23 | *.ctxt 24 | 25 | # Mobile Tools for Java (J2ME) 26 | .mtj.tmp/ 27 | 28 | # Package Files # 29 | *.jar 30 | *.war 31 | *.ear 32 | *.zip 33 | *.tar.gz 34 | *.rar 35 | 36 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 37 | hs_err_pid* 38 | ### JetBrains template 39 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 40 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 41 | 42 | # IDE 43 | .idea/ 44 | *.iml 45 | 46 | ## File-based project format: 47 | *.iws 48 | 49 | ## Plugin-specific files: 50 | 51 | # IntelliJ 52 | /out/ 53 | 54 | # JIRA plugin 55 | atlassian-ide-plugin.xml 56 | 57 | # Crashlytics plugin (for Android Studio and IntelliJ) 58 | com_crashlytics_export_strings.xml 59 | crashlytics.properties 60 | crashlytics-build.properties 61 | fabric.properties 62 | 63 | -------------------------------------------------------------------------------- /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 | * 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. 7 | give it a try. 8 | * I gained this substantial speed improvement by using the lucene index directly 9 | * I developed it for my workplace which needs to pick KNN from a set of ~4M vectors. our current ES setup is able to answer this in ~80ms 10 | * **Note: Elasticsearch introduced a similar vector similarity functions in version 7.4 and above. [Elasticsearch version 8.0] (https://www.elastic.co/blog/introducing-approximate-nearest-neighbor-search-in-elasticsearch-8-0) includes native ANN support. This makes this plug-in obsolete for new Elasticsearch versions, unless for some reason their implementation is slower than this plugin**. 11 | 12 | 13 | ## Elasticsearch version 14 | * master branch is designed for Elasticsearch 5.6.9. 15 | * for Elasticsearch 7.9.0 use branch `es-7.9.0` 16 | * for Elasticsearch 7.5.2 use branch `es-7.5.2` 17 | * for Elasticsearch 7.5.0 use branch `es-7.5.0` 18 | * for Elasticsearch 7.2.1 use branch `es-7.2.1` 19 | * for Elasticsearch 7.1.0 use branch `es-7.1` 20 | * for Elasticsearch 6.8.1 use branch `es-6.8.1` 21 | * for Elasticsearch 5.2.2 use branch `es-5.2.2` 22 | * for Elasticsearch 2.4.4 use branch `es-2.4.4` 23 | 24 | 25 | ## Maven configuration 26 | * Clone the project 27 | * `mvn package` to compile the plugin as a zip file 28 | * In the Elasticsearch root folder run `./bin/elasticsearch-plugin install file://` to install plugin. for example: `./bin/elasticsearch-plugin install file:///Users/lior/dev/fast-elasticsearch-vector-scoring/target/releases/elasticsearch-binary-vector-scoring-5.6.9.zip` 29 | 30 | 31 | 32 | ## Usage 33 | 34 | ### Documents 35 | * Each document you score should have a field containing the base64 representation of your vector. for example: 36 | ``` 37 | { 38 | "id": 1, 39 | .... 40 | "embedding_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=" 41 | } 42 | ``` 43 | * Use this field mapping: 44 | ``` 45 | "embedding_vector": { 46 | "type": "binary", 47 | "doc_values": true 48 | } 49 | ``` 50 | * The vector can be of any dimension 51 | 52 | ### Converting a vector to Base64 53 | to convert an array of float32 to a base64 string we use these example methods: 54 | 55 | **Java** 56 | ``` 57 | public static float[] convertBase64ToArray(String base64Str) { 58 | final byte[] decode = Base64.getDecoder().decode(base64Str.getBytes()); 59 | final FloatBuffer floatBuffer = ByteBuffer.wrap(decode).asFloatBuffer(); 60 | final float[] dims = new float[floatBuffer.capacity()]; 61 | floatBuffer.get(dims); 62 | 63 | return dims; 64 | } 65 | 66 | public static String convertArrayToBase64(float[] array) { 67 | final int capacity = Float.BYTES * array.length; 68 | final ByteBuffer bb = ByteBuffer.allocate(capacity); 69 | for (float v : array) { 70 | bb.putFloat(v); 71 | } 72 | bb.rewind(); 73 | final ByteBuffer encodedBB = Base64.getEncoder().encode(bb); 74 | 75 | return new String(encodedBB.array()); 76 | } 77 | ``` 78 | **Python** 79 | ``` 80 | import base64 81 | import numpy as np 82 | 83 | dfloat32 = np.dtype('>f4') 84 | 85 | def decode_float_list(base64_string): 86 | bytes = base64.b64decode(base64_string) 87 | return np.frombuffer(bytes, dtype=dfloat32).tolist() 88 | 89 | def encode_array(arr): 90 | base64_str = base64.b64encode(np.array(arr).astype(dfloat32)).decode("utf-8") 91 | return base64_str 92 | ``` 93 | 94 | **Ruby** 95 | ``` 96 | require 'base64' 97 | 98 | def decode_float_list(base64_string) 99 | Base64.strict_decode64(base64_string).unpack('g*') 100 | end 101 | 102 | def encode_array(arr) 103 | Base64.strict_encode64(arr.pack('g*')) 104 | end 105 | ``` 106 | 107 | **Go** 108 | ``` 109 | import( 110 | "math" 111 | "encoding/binary" 112 | "encoding/base64" 113 | ) 114 | 115 | func convertArrayToBase64(array []float32) string { 116 | bytes := make([]byte, 0, 4*len(array)) 117 | for _, a := range array { 118 | bits := math.Float32bits(a) 119 | b := make([]byte, 4) 120 | binary.BigEndian.PutUint32(b, bits) 121 | bytes = append(bytes, b...) 122 | } 123 | 124 | encoded := base64.StdEncoding.EncodeToString(bytes) 125 | return encoded 126 | } 127 | 128 | func convertBase64ToArray(base64Str string) ([]float32, error) { 129 | decoded, err := base64.StdEncoding.DecodeString(base64Str) 130 | if err != nil { 131 | return nil, err 132 | } 133 | 134 | length := len(decoded) 135 | array := make([]float32, 0, length/4) 136 | 137 | for i := 0; i < len(decoded); i += 4 { 138 | bits := binary.BigEndian.Uint32(decoded[i : i+4]) 139 | f := math.Float32frombits(bits) 140 | array = append(array, f) 141 | } 142 | return array, nil 143 | } 144 | ``` 145 | 146 | ### Querying 147 | * For querying the 100 KNN documents use this POST message on your ES index: 148 | 149 | 150 | For ES 5.X and ES 7.X: 151 | ``` 152 | { 153 | "query": { 154 | "function_score": { 155 | "boost_mode": "replace", 156 | "script_score": { 157 | "script": { 158 | "source": "binary_vector_score", 159 | "lang": "knn", 160 | "params": { 161 | "cosine": false, 162 | "field": "embedding_vector", 163 | "vector": [ 164 | -0.09217305481433868, 0.010635560378432274, -0.02878434956073761, 0.06988169997930527, 0.1273992955684662, -0.023723633959889412, 0.05490724742412567, -0.12124507874250412, -0.023694118484854698, 0.014595639891922474, 0.1471538096666336, 0.044936809688806534, -0.02795785665512085, -0.05665992572903633, -0.2441125512123108, 0.2755320072174072, 0.11451690644025803, 0.20242854952812195, -0.1387604922056198, 0.05219579488039017, 0.1145530641078949, 0.09967200458049774, 0.2161576747894287, 0.06157230958342552, 0.10350126028060913, 0.20387393236160278, 0.1367097795009613, 0.02070528082549572, 0.19238869845867157, 0.059613026678562164, 0.014012521132826805, 0.16701748967170715, 0.04985826835036278, -0.10990987718105316, -0.12032567709684372, -0.1450948715209961, 0.13585780560970306, 0.037511035799980164, 0.04251480475068092, 0.10693439096212387, -0.08861573040485382, -0.07457160204648972, 0.0549330934882164, 0.19136285781860352, 0.03346432000398636, -0.03652812913060188, -0.1902569830417633, 0.03250952064990997, -0.3061246871948242, 0.05219300463795662, -0.07879918068647385, 0.1403723508119583, -0.08893408626317978, -0.24330253899097443, -0.07105310261249542, -0.18161986768245697, 0.15501035749912262, -0.216160386800766, -0.06377710402011871, -0.07671763002872467, 0.05360138416290283, -0.052845533937215805, -0.02905619889497757, 0.08279753476381302 165 | ] 166 | } 167 | } 168 | } 169 | } 170 | }, 171 | "size": 100 172 | } 173 | ``` 174 | 175 | 176 | For ES 2.X: 177 | 178 | ``` 179 | { 180 | "query": { 181 | "function_score": { 182 | "boost_mode": "replace", 183 | "script_score": { 184 | "lang": "knn", 185 | "params": { 186 | "cosine": false, 187 | "field": "embedding_vector", 188 | "vector": [ 189 | -0.09217305481433868, 0.010635560378432274, -0.02878434956073761, 0.06988169997930527, 0.1273992955684662, -0.023723633959889412, 0.05490724742412567, -0.12124507874250412, -0.023694118484854698, 0.014595639891922474, 0.1471538096666336, 0.044936809688806534, -0.02795785665512085, -0.05665992572903633, -0.2441125512123108, 0.2755320072174072, 0.11451690644025803, 0.20242854952812195, -0.1387604922056198, 0.05219579488039017, 0.1145530641078949, 0.09967200458049774, 0.2161576747894287, 0.06157230958342552, 0.10350126028060913, 0.20387393236160278, 0.1367097795009613, 0.02070528082549572, 0.19238869845867157, 0.059613026678562164, 0.014012521132826805, 0.16701748967170715, 0.04985826835036278, -0.10990987718105316, -0.12032567709684372, -0.1450948715209961, 0.13585780560970306, 0.037511035799980164, 0.04251480475068092, 0.10693439096212387, -0.08861573040485382, -0.07457160204648972, 0.0549330934882164, 0.19136285781860352, 0.03346432000398636, -0.03652812913060188, -0.1902569830417633, 0.03250952064990997, -0.3061246871948242, 0.05219300463795662, -0.07879918068647385, 0.1403723508119583, -0.08893408626317978, -0.24330253899097443, -0.07105310261249542, -0.18161986768245697, 0.15501035749912262, -0.216160386800766, -0.06377710402011871, -0.07671763002872467, 0.05360138416290283, -0.052845533937215805, -0.02905619889497757, 0.08279753476381302 190 | ] 191 | }, 192 | "script": "binary_vector_score" 193 | } 194 | } 195 | }, 196 | "size": 100 197 | } 198 | ``` 199 | * The example above shows a vector of 64 dimensions 200 | * Parameters: 201 | 1. `field`: The field containing the base64 vector. 202 | 2. `cosine`: Boolean. if true - use cosine-similarity, else use dot-product. 203 | 3. `vector`: The vector (comma separated) to compare to. 204 | 205 | * Note **for ElasticSearch 6 and 7 only**: 206 | Because scores produced by the script_score function must be non-negative on elasticsearch 7, We convert the dot product score and cosine similarity score by using these simple equations: 207 | (changed dot product) = e^(original dot product) 208 | (changed cosine similarity) = ((original cosine similarity) + 1) / 2 209 | 210 | We can use these simple equation to convert them to original score. 211 | (original dot product) = ln(changed dot product) 212 | (original cosine similarity) = (changed cosine similarity) * 2 - 1 213 | 214 | * Question: I've encountered the error `java.lang.IllegalStateException: binaryEmbeddingReader can't be null` while running the query. what should I do? 215 | 216 | Answer: this error happens when the plugin fails to access the field you specified in the `field` parameter in at least one of the documents. 217 | 218 | To solve it: 219 | 220 | * make sure that **all** the documents in your index contains the filed you specified in the `field` parameter. 221 | see more details [here](https://github.com/lior-k/fast-elasticsearch-vector-scoring/issues/6) 222 | * make sure that the filed you specified in the `field` parameter has a `binary` type in the index mapping 223 | 224 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | elasticsearch-binary-vector-scoring 8 | com.liorkn.elasticsearch 9 | elasticsearch-binary-vector-scoring 10 | 5.6.9 11 | ElasticSearch Plugin for Binary Vector Scoring 12 | 13 | 14 | 15 | The Apache Software License, Version 2.0 16 | http://www.apache.org/licenses/LICENSE-2.0.txt 17 | repo 18 | 19 | 20 | 21 | 22 | 23 | com.liorkn.elasticsearch.plugin.VectorScoringPlugin 24 | 25 | 26 | ${project.basedir}/src/main/resources/license-check/vector_scoring_license_header.txt 27 | ${project.basedir}/src/main/resources/license-check/license_header_definition.xml 28 | 29 | warn 30 | 5.6.9 31 | 2.4 32 | 4.4.8 33 | 4.12 34 | 2.9.10.8 35 | 36 | 37 | 38 | 39 | 40 | org.apache.logging.log4j 41 | log4j-api 42 | 2.17.1 43 | test 44 | 45 | 46 | org.apache.logging.log4j 47 | log4j-core 48 | 2.13.2 49 | test 50 | 51 | 52 | org.elasticsearch 53 | elasticsearch 54 | ${elasticsearch.version} 55 | provided 56 | 57 | 58 | 59 | junit 60 | junit 61 | ${junit.version} 62 | test 63 | 64 | 65 | 66 | org.elasticsearch.plugin 67 | transport-netty3-client 68 | ${elasticsearch.version} 69 | test 70 | 71 | 72 | 73 | org.codelibs.elasticsearch.module 74 | reindex 75 | ${elasticsearch.version} 76 | test 77 | 78 | 79 | org.slf4j 80 | slf4j-log4j12 81 | 82 | 83 | log4j 84 | log4j 85 | 86 | 87 | 88 | 89 | org.codelibs.elasticsearch.module 90 | lang-painless 91 | ${elasticsearch.version} 92 | test 93 | 94 | 95 | commons-io 96 | commons-io 97 | ${commons-io.version} 98 | test 99 | 100 | 101 | org.apache.httpcomponents 102 | httpcore 103 | ${httpcore.version} 104 | test 105 | 106 | 107 | org.elasticsearch.client 108 | elasticsearch-rest-client 109 | ${elasticsearch.version} 110 | test 111 | 112 | 113 | org.apache.httpcomponents 114 | httpclient 115 | 116 | 117 | org.apache.httpcomponents 118 | httpclient 119 | 120 | 121 | org.apache.httpcomponents 122 | httpcore 123 | 124 | 125 | commons-codec 126 | commons-codec 127 | 128 | 129 | commons-logging 130 | commons-logging 131 | 132 | 133 | 134 | 135 | 136 | com.fasterxml.jackson.core 137 | jackson-databind 138 | ${jackson.version} 139 | test 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | oss-snapshots 148 | Sonatype OSS Snapshots 149 | https://oss.sonatype.org/content/repositories/snapshots/ 150 | 151 | 152 | 153 | 154 | 155 | 156 | src/main/resources 157 | true 158 | 159 | plugin-descriptor.properties 160 | 161 | 162 | 163 | 164 | 165 | org.apache.maven.plugins 166 | maven-compiler-plugin 167 | 168 | 1.8 169 | 1.8 170 | 171 | 172 | 173 | org.apache.maven.plugins 174 | maven-assembly-plugin 175 | 176 | false 177 | ${project.build.directory}/releases/ 178 | ${basedir}/src/main/assemblies/plugin.xml 179 | 180 | 181 | 182 | package 183 | 184 | single 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | -------------------------------------------------------------------------------- /src/main/assemblies/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | plugin 4 | 5 | zip 6 | 7 | true 8 | elasticsearch 9 | 10 | 11 | / 12 | true 13 | true 14 | 15 | org.elasticsearch:elasticsearch 16 | org.apache.lucene:* 17 | 18 | 19 | 20 | 21 | 22 | src/main/resources 23 | / 24 | true 25 | 26 | plugin-descriptor.properties 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/main/java/com/liorkn/elasticsearch/Util.java: -------------------------------------------------------------------------------- 1 | package com.liorkn.elasticsearch; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.FloatBuffer; 5 | import java.util.Base64; 6 | 7 | /** 8 | * Created by Lior Knaany on 4/7/18. 9 | */ 10 | public class Util { 11 | 12 | public static float[] convertBase64ToArray(String base64Str) { 13 | final byte[] decode = Base64.getDecoder().decode(base64Str.getBytes()); 14 | final FloatBuffer floatBuffer = ByteBuffer.wrap(decode).asFloatBuffer(); 15 | final float[] dims = new float[floatBuffer.capacity()]; 16 | floatBuffer.get(dims); 17 | 18 | return dims; 19 | } 20 | 21 | public static String convertArrayToBase64(float[] array) { 22 | final int capacity = Float.BYTES * array.length; 23 | final ByteBuffer bb = ByteBuffer.allocate(capacity); 24 | for (double v : array) { 25 | bb.putFloat((float) v); 26 | } 27 | bb.rewind(); 28 | final ByteBuffer encodedBB = Base64.getEncoder().encode(bb); 29 | 30 | return new String(encodedBB.array()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/liorkn/elasticsearch/plugin/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.liorkn.elasticsearch.plugin; 15 | 16 | import com.liorkn.elasticsearch.service.VectorScoringScriptEngineService; 17 | 18 | import org.elasticsearch.common.settings.Settings; 19 | import org.elasticsearch.plugins.Plugin; 20 | import org.elasticsearch.plugins.ScriptPlugin; 21 | import org.elasticsearch.script.ScriptEngineService; 22 | 23 | /** 24 | * This class is instantiated when Elasticsearch loads the plugin for the 25 | * first time. If you change the name of this plugin, make sure to update 26 | * src/main/resources/es-plugin.properties file that points to this class. 27 | */ 28 | public final class VectorScoringPlugin extends Plugin implements ScriptPlugin { 29 | 30 | public final ScriptEngineService getScriptEngineService(Settings settings) { 31 | return new VectorScoringScriptEngineService(settings); 32 | } 33 | 34 | 35 | } -------------------------------------------------------------------------------- /src/main/java/com/liorkn/elasticsearch/script/VectorScoreScript.java: -------------------------------------------------------------------------------- 1 | /* 2 | Based on: https://discuss.elastic.co/t/vector-scoring/85227/4 3 | and https://github.com/MLnick/elasticsearch-vector-scoring 4 | 5 | another slower implementation using strings: https://github.com/ginobefun/elasticsearch-feature-vector-scoring 6 | 7 | storing arrays is no luck - lucine index doesn't keep the array members orders 8 | https://www.elastic.co/guide/en/elasticsearch/guide/current/complex-core-fields.html 9 | 10 | Delimited Payload Token Filter: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/analysis-delimited-payload-tokenfilter.html 11 | */ 12 | 13 | package com.liorkn.elasticsearch.script; 14 | 15 | import com.liorkn.elasticsearch.Util; 16 | import org.apache.lucene.index.BinaryDocValues; 17 | import org.apache.lucene.store.ByteArrayDataInput; 18 | import org.elasticsearch.common.Nullable; 19 | import org.elasticsearch.script.ExecutableScript; 20 | import org.elasticsearch.script.LeafSearchScript; 21 | import org.elasticsearch.script.ScriptException; 22 | 23 | import java.util.ArrayList; 24 | import java.util.Map; 25 | 26 | 27 | /** 28 | * Script that scores documents based on cosine similarity embedding vectors. 29 | */ 30 | public final class VectorScoreScript implements LeafSearchScript, ExecutableScript { 31 | 32 | // the field containing the vectors to be scored against 33 | public final String field; 34 | 35 | private int docId; 36 | private BinaryDocValues binaryEmbeddingReader; 37 | 38 | private final float[] inputVector; 39 | private final float magnitude; 40 | 41 | private final boolean cosine; 42 | 43 | @Override 44 | public final Object run() { 45 | return runAsDouble(); 46 | } 47 | 48 | @Override 49 | public long runAsLong() { 50 | return (long) runAsDouble(); 51 | } 52 | 53 | /** 54 | * Called for each document 55 | * @return cosine similarity of the current document against the input inputVector 56 | */ 57 | @Override 58 | public double runAsDouble() { 59 | final byte[] bytes = binaryEmbeddingReader.get(docId).bytes; 60 | final ByteArrayDataInput input = new ByteArrayDataInput(bytes); 61 | 62 | // MUST appear hear since it affect the next calls 63 | input.readVInt(); // returns the number of values which should be 1 64 | input.readVInt(); // returns the number of bytes to read 65 | 66 | float score = 0; 67 | 68 | if(cosine) { 69 | float docVectorNorm = 0.0f; 70 | 71 | for (int i = 0; i < inputVector.length; i++) { 72 | float v = Float.intBitsToFloat(input.readInt()); 73 | docVectorNorm += v * v; // inputVector norm 74 | score += v * inputVector[i]; // dot product 75 | } 76 | 77 | if (docVectorNorm == 0 || magnitude == 0) { 78 | return 0f; 79 | } else { 80 | return score / (Math.sqrt(docVectorNorm) * magnitude); 81 | } 82 | } else { 83 | for (int i = 0; i < inputVector.length; i++) { 84 | float v = Float.intBitsToFloat(input.readInt()); 85 | score += v * inputVector[i]; // dot product 86 | } 87 | 88 | return score; 89 | } 90 | } 91 | 92 | @Override 93 | public void setNextVar(String name, Object value) {} 94 | 95 | @Override 96 | public void setDocument(int docId) { 97 | this.docId = docId; 98 | } 99 | 100 | public void setBinaryEmbeddingReader(BinaryDocValues binaryEmbeddingReader) { 101 | if(binaryEmbeddingReader == null) { 102 | throw new IllegalStateException("binaryEmbeddingReader can't be null"); 103 | } 104 | this.binaryEmbeddingReader = binaryEmbeddingReader; 105 | } 106 | 107 | /** 108 | * Factory that is registered in 109 | * {@link VectorScoringPlugin#onModule(org.elasticsearch.script.ScriptModule)} 110 | * method when the plugin is loaded. 111 | */ 112 | public static class Factory { 113 | 114 | /** 115 | * This method is called for every search on every shard. 116 | * 117 | * @param params 118 | * list of script parameters passed with the query 119 | * @return new native script 120 | */ 121 | public ExecutableScript newScript(@Nullable Map params) throws ScriptException { 122 | return new VectorScoreScript(params); 123 | } 124 | 125 | /** 126 | * Indicates if document scores may be needed by the produced scripts. 127 | * 128 | * @return {@code true} if scores are needed. 129 | */ 130 | public boolean needsScores() { 131 | return false; 132 | } 133 | } 134 | 135 | /** 136 | * Init 137 | * @param params index that a scored are placed in this parameter. Initialize them here. 138 | */ 139 | @SuppressWarnings("unchecked") 140 | public VectorScoreScript(Map params) { 141 | final Object cosineBool = params.get("cosine"); 142 | cosine = cosineBool != null ? 143 | (boolean)cosineBool : 144 | true; 145 | 146 | final Object field = params.get("field"); 147 | if (field == null) 148 | throw new IllegalArgumentException("binary_vector_score script requires field input"); 149 | this.field = field.toString(); 150 | 151 | // get query inputVector - convert to primitive 152 | final Object vector = params.get("vector"); 153 | if(vector != null) { 154 | final ArrayList tmp = (ArrayList) vector; 155 | inputVector = new float[tmp.size()]; 156 | for (int i = 0; i < inputVector.length; i++) { 157 | inputVector[i] = tmp.get(i).floatValue(); 158 | } 159 | } else { 160 | final Object encodedVector = params.get("encoded_vector"); 161 | if(encodedVector == null) { 162 | throw new IllegalArgumentException("Must have at 'vector' or 'encoded_vector' as a parameter"); 163 | } 164 | inputVector = Util.convertBase64ToArray((String) encodedVector); 165 | } 166 | 167 | if(cosine) { 168 | // calc magnitude 169 | float queryVectorNorm = 0.0f; 170 | // compute query inputVector norm once 171 | for (float v: inputVector) { 172 | queryVectorNorm += v * v; 173 | } 174 | magnitude = (float) Math.sqrt(queryVectorNorm); 175 | } else { 176 | magnitude = 0.0f; 177 | } 178 | } 179 | } -------------------------------------------------------------------------------- /src/main/java/com/liorkn/elasticsearch/service/VectorScoringScriptEngineService.java: -------------------------------------------------------------------------------- 1 | package com.liorkn.elasticsearch.service; 2 | 3 | import com.liorkn.elasticsearch.script.VectorScoreScript; 4 | import org.apache.lucene.index.LeafReaderContext; 5 | import org.elasticsearch.common.Nullable; 6 | import org.elasticsearch.common.component.AbstractComponent; 7 | import org.elasticsearch.common.inject.Inject; 8 | import org.elasticsearch.common.settings.Settings; 9 | import org.elasticsearch.script.CompiledScript; 10 | import org.elasticsearch.script.ExecutableScript; 11 | import org.elasticsearch.script.LeafSearchScript; 12 | import org.elasticsearch.script.ScriptEngineService; 13 | import org.elasticsearch.script.SearchScript; 14 | import org.elasticsearch.search.lookup.SearchLookup; 15 | 16 | import java.io.IOException; 17 | import java.util.Map; 18 | 19 | /** 20 | * Created by Lior Knaany on 5/14/17. 21 | */ 22 | public class VectorScoringScriptEngineService extends AbstractComponent implements ScriptEngineService{ 23 | 24 | public static final String NAME = "knn"; 25 | 26 | @Inject 27 | public VectorScoringScriptEngineService(Settings settings) { 28 | super(settings); 29 | } 30 | 31 | @Override 32 | public Object compile(String scriptName, String scriptSource, Map params) { 33 | return new VectorScoreScript.Factory(); 34 | } 35 | 36 | @Override 37 | public boolean isInlineScriptEnabled() { 38 | return true; 39 | } 40 | 41 | @Override 42 | public String getType() { 43 | return NAME; 44 | } 45 | 46 | @Override 47 | public String getExtension() { 48 | return NAME; 49 | } 50 | 51 | @Override 52 | public ExecutableScript executable(CompiledScript compiledScript, @Nullable Map vars) { 53 | VectorScoreScript.Factory scriptFactory = (VectorScoreScript.Factory) compiledScript.compiled(); 54 | return scriptFactory.newScript(vars); 55 | } 56 | 57 | @Override 58 | public SearchScript search(CompiledScript compiledScript, final SearchLookup lookup, @Nullable final Map vars) { 59 | final VectorScoreScript.Factory scriptFactory = (VectorScoreScript.Factory) compiledScript.compiled(); 60 | final VectorScoreScript script = (VectorScoreScript) scriptFactory.newScript(vars); 61 | return new SearchScript() { 62 | @Override 63 | public LeafSearchScript getLeafSearchScript(LeafReaderContext context) throws IOException { 64 | script.setBinaryEmbeddingReader(context.reader().getBinaryDocValues(script.field)); 65 | return script; 66 | } 67 | @Override 68 | public boolean needsScores() { 69 | return scriptFactory.needsScores(); 70 | } 71 | }; 72 | } 73 | 74 | @Override 75 | public void close() { 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/resources/license-check/license_header_definition.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /* 5 | * 6 | */ 7 | (\s|\t)*/\*.*$ 8 | .*\*/(\s|\t)*$ 9 | false 10 | true 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/license-check/vector_scoring_license_header.txt: -------------------------------------------------------------------------------- 1 | Copyright [2017] [Lior Knaany] 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /src/main/resources/plugin-descriptor.properties: -------------------------------------------------------------------------------- 1 | name=${project.name} 2 | description=${project.description} 3 | version=${project.version} 4 | jvm=true 5 | classname=${elasticsearch.plugin.classname} 6 | java.version=1.8 7 | elasticsearch.version=${elasticsearch.version} -------------------------------------------------------------------------------- /src/test/java/com/liorkn/elasticsearch/EmbeddedElasticsearchServer.java: -------------------------------------------------------------------------------- 1 | package com.liorkn.elasticsearch; 2 | 3 | import com.liorkn.elasticsearch.plugin.VectorScoringPlugin; 4 | import org.apache.commons.io.FileUtils; 5 | import org.elasticsearch.client.Client; 6 | import org.elasticsearch.common.settings.Settings; 7 | import org.elasticsearch.http.BindHttpException; 8 | import org.elasticsearch.index.reindex.ReindexPlugin; 9 | import org.elasticsearch.node.Node; 10 | import org.elasticsearch.node.NodeValidationException; 11 | import org.elasticsearch.painless.PainlessPlugin; 12 | import org.elasticsearch.transport.Netty3Plugin; 13 | 14 | import java.io.File; 15 | import java.io.IOException; 16 | import java.util.Arrays; 17 | import java.util.Random; 18 | 19 | public class EmbeddedElasticsearchServer { 20 | private static final Random RANDOM = new Random(); 21 | private static final String DEFAULT_DATA_DIRECTORY = "target/elasticsearch-data"; 22 | private static final String DEFAULT_HOME_DIRECTORY = "target/elasticsearch-home"; 23 | private static final int MAX_PORT_RETRIES = 20; 24 | 25 | private Node node; 26 | private int port; 27 | private String dataDirectory; 28 | 29 | public EmbeddedElasticsearchServer() throws NodeValidationException { 30 | this(DEFAULT_DATA_DIRECTORY); 31 | } 32 | 33 | private EmbeddedElasticsearchServer(String dataDirectory) throws NodeValidationException { 34 | this(dataDirectory, randomPort()); 35 | } 36 | 37 | private EmbeddedElasticsearchServer(String defaultDataDirectory, int port) throws NodeValidationException { 38 | this.dataDirectory = defaultDataDirectory; 39 | this.port = port; 40 | 41 | Settings.Builder settings = Settings.builder() 42 | .put("http.enabled", "true") 43 | .put("transport.type", "local") 44 | .put("http.type", "netty3") 45 | .put("path.data", dataDirectory) 46 | .put("path.home", DEFAULT_HOME_DIRECTORY) 47 | .put("script.inline", "on") 48 | .put("node.max_local_storage_nodes", 10000) 49 | .put("script.stored", "on"); 50 | 51 | startNodeInAvailablePort(settings); 52 | } 53 | 54 | private void startNodeInAvailablePort(Settings.Builder settings) throws NodeValidationException { 55 | int findFreePortRetries = MAX_PORT_RETRIES; 56 | boolean success = false; 57 | 58 | while(!success) { 59 | try { 60 | settings.put("http.port", String.valueOf(this.port)); 61 | 62 | // this a hack in order to load Groovy plug in since we want to enable the usage of scripts 63 | node = new NodeExt(settings.build() , Arrays.asList(Netty3Plugin.class, PainlessPlugin.class, ReindexPlugin.class, VectorScoringPlugin.class)); 64 | node.start(); 65 | success = true; 66 | System.out.println(EmbeddedElasticsearchServer.class.getName() + ": Using port: " + this.port); 67 | } catch (BindHttpException exception) { 68 | if(findFreePortRetries == 0) { 69 | System.out.println("Could not find any free port in range: [" + (this.port - MAX_PORT_RETRIES) + " - " + this.port+"]"); 70 | throw exception; 71 | } 72 | findFreePortRetries--; 73 | System.out.println("Port already in use (" + this.port + "). Trying another port..."); 74 | this.port = randomPort(); 75 | } 76 | } 77 | } 78 | 79 | public String getUrl() { 80 | return "http://localhost:" + port; 81 | } 82 | 83 | public Client getClient() { 84 | return node.client(); 85 | } 86 | 87 | public void shutdown() { 88 | if ( node != null ) 89 | try { 90 | node.close(); 91 | } catch (IOException e) { 92 | e.printStackTrace(); 93 | } 94 | deleteDataDirectory(); 95 | } 96 | 97 | private void deleteDataDirectory() { 98 | try { 99 | FileUtils.deleteDirectory(new File(dataDirectory)); 100 | } catch (IOException e) { 101 | throw new RuntimeException("Could not delete data directory of embedded elasticsearch server", e); 102 | } 103 | } 104 | 105 | private static int randomPort() { 106 | return RANDOM.nextInt(500) + 4200; 107 | } 108 | 109 | public int getPort() { 110 | return port; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/test/java/com/liorkn/elasticsearch/NodeExt.java: -------------------------------------------------------------------------------- 1 | package com.liorkn.elasticsearch; 2 | 3 | import org.elasticsearch.common.settings.Settings; 4 | import org.elasticsearch.node.InternalSettingsPreparer; 5 | import org.elasticsearch.node.Node; 6 | import org.elasticsearch.plugins.Plugin; 7 | 8 | import java.util.Collection; 9 | 10 | /** 11 | * a really god explanation for this is on: https://discuss.elastic.co/t/unsupported-http-type-netty3-when-trying-to-start-embedded-elasticsearch-node/69669/7 12 | */ 13 | public class NodeExt extends Node { 14 | 15 | public NodeExt(Settings preparedSettings, Collection> classpathPlugins) { 16 | super(InternalSettingsPreparer.prepareEnvironment(preparedSettings, null), 17 | classpathPlugins); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/liorkn/elasticsearch/PluginTest.java: -------------------------------------------------------------------------------- 1 | package com.liorkn.elasticsearch; 2 | 3 | import com.fasterxml.jackson.core.JsonParser; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.fasterxml.jackson.databind.node.ArrayNode; 6 | import org.apache.http.HttpHost; 7 | import org.apache.http.entity.ContentType; 8 | import org.apache.http.entity.StringEntity; 9 | import org.apache.http.nio.entity.NStringEntity; 10 | import org.apache.http.util.EntityUtils; 11 | import org.elasticsearch.client.Response; 12 | import org.elasticsearch.client.RestClient; 13 | import org.junit.AfterClass; 14 | import org.junit.Assert; 15 | import org.junit.BeforeClass; 16 | import org.junit.Test; 17 | 18 | import java.io.IOException; 19 | import java.util.Collections; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | /** 24 | * Created by Lior Knaany on 4/7/18. 25 | */ 26 | public class PluginTest { 27 | 28 | private static EmbeddedElasticsearchServer esServer; 29 | private static RestClient esClient; 30 | 31 | @BeforeClass 32 | public static void init() throws Exception { 33 | esServer = new EmbeddedElasticsearchServer(); 34 | esClient = RestClient.builder(new HttpHost("localhost", esServer.getPort(), "http")).build(); 35 | 36 | // delete test index if exists 37 | try { 38 | esClient.performRequest("DELETE", "/test", Collections.emptyMap()); 39 | } catch (Exception e) {} 40 | 41 | // create test index 42 | String mappingJson = "{\n" + 43 | " \"mappings\": {\n" + 44 | " \"type\": {\n" + 45 | " \"properties\": {\n" + 46 | " \"embedding_vector\": {\n" + 47 | " \"doc_values\": true,\n" + 48 | " \"type\": \"binary\"\n" + 49 | " },\n" + 50 | " \"job_id\": {\n" + 51 | " \"type\": \"long\"\n" + 52 | " },\n" + 53 | " \"vector\": {\n" + 54 | " \"type\": \"float\"\n" + 55 | " }\n" + 56 | " }\n" + 57 | " }\n" + 58 | " }\n" + 59 | "}"; 60 | esClient.performRequest("PUT", "/test", Collections.emptyMap(), new NStringEntity(mappingJson, ContentType.APPLICATION_JSON)); 61 | } 62 | 63 | public static final ObjectMapper mapper = new ObjectMapper(); 64 | static { 65 | mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); 66 | mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); 67 | } 68 | 69 | 70 | @Test 71 | public void test() throws Exception { 72 | final Map params = new HashMap<>(); 73 | params.put("refresh", "true"); 74 | final TestObject[] objs = {new TestObject(1, new float[] {0.0f, 0.5f, 1.0f}), 75 | new TestObject(2, new float[] {0.2f, 0.6f, 0.99f})}; 76 | 77 | for (int i = 0; i < objs.length; i++) { 78 | final TestObject t = objs[i]; 79 | final String json = mapper.writeValueAsString(t); 80 | System.out.println(json); 81 | final Response put = esClient.performRequest("PUT", "/test/type/" + t.jobId, params, new StringEntity(json, ContentType.APPLICATION_JSON)); 82 | System.out.println(put); 83 | System.out.println(EntityUtils.toString(put.getEntity())); 84 | final int statusCode = put.getStatusLine().getStatusCode(); 85 | Assert.assertTrue(statusCode == 200 || statusCode == 201); 86 | } 87 | 88 | // Test cosine score function 89 | String body = "{" + 90 | " \"query\": {" + 91 | " \"function_score\": {" + 92 | " \"boost_mode\": \"replace\"," + 93 | " \"script_score\": {" + 94 | " \"script\": {" + 95 | " \"source\": \"binary_vector_score\"," + 96 | " \"lang\": \"knn\"," + 97 | " \"params\": {" + 98 | " \"cosine\": true," + 99 | " \"field\": \"embedding_vector\"," + 100 | " \"vector\": [" + 101 | " 0.1, 0.2, 0.3" + 102 | " ]" + 103 | " }" + 104 | " }" + 105 | " }" + 106 | " }" + 107 | " }," + 108 | " \"size\": 100" + 109 | "}"; 110 | final Response res = esClient.performRequest("POST", "/test/_search", Collections.emptyMap(), new NStringEntity(body, ContentType.APPLICATION_JSON)); 111 | System.out.println(res); 112 | final String resBody = EntityUtils.toString(res.getEntity()); 113 | System.out.println(resBody); 114 | Assert.assertEquals("search should return status code 200", 200, res.getStatusLine().getStatusCode()); 115 | Assert.assertTrue(String.format("There should be %d documents in the search response", objs.length), resBody.contains("\"hits\":{\"total\":" + objs.length)); 116 | // Testing Scores 117 | final ArrayNode hitsJson = (ArrayNode)mapper.readTree(resBody).get("hits").get("hits"); 118 | Assert.assertEquals(0.9941734, hitsJson.get(0).get("_score").asDouble(), 0); 119 | Assert.assertEquals(0.95618284, hitsJson.get(1).get("_score").asDouble(), 0); 120 | } 121 | 122 | @AfterClass 123 | public static void shutdown() { 124 | try { 125 | esClient.close(); 126 | esServer.shutdown(); 127 | } catch (IOException e) { 128 | e.printStackTrace(); 129 | } 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/test/java/com/liorkn/elasticsearch/TestObject.java: -------------------------------------------------------------------------------- 1 | package com.liorkn.elasticsearch; 2 | 3 | import com.fasterxml.jackson.databind.PropertyNamingStrategy; 4 | import com.fasterxml.jackson.databind.annotation.JsonNaming; 5 | 6 | /** 7 | * Created by Lior Knaany on 4/7/18. 8 | */ 9 | @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) 10 | public class TestObject { 11 | int jobId; 12 | String embeddingVector; 13 | float[] vector; 14 | 15 | public int getJobId() { 16 | return jobId; 17 | } 18 | 19 | public String getEmbeddingVector() { 20 | return embeddingVector; 21 | } 22 | 23 | public float[] getVector() { 24 | return vector; 25 | } 26 | 27 | public TestObject(int jobId, float[] vector) { 28 | this.jobId = jobId; 29 | this.vector = vector; 30 | this.embeddingVector = Util.convertArrayToBase64(vector); 31 | } 32 | } 33 | --------------------------------------------------------------------------------