├── licenses ├── duke-NOTICE.txt ├── duke-1.2.jar.sha1 ├── mapdb-0.9.9.jar.sha1 ├── mapdb-NOTICE.txt ├── duke-LICENSE.txt └── mapdb-LICENSE.txt ├── .travis.yml ├── src ├── test │ ├── resources │ │ ├── log4j.properties │ │ └── rest-api-spec │ │ │ └── test │ │ │ └── nativescript │ │ │ └── 10_test_loaded.yaml │ └── java │ │ └── org │ │ └── yaba │ │ └── entity │ │ ├── plugin │ │ └── EntityResolutionRestIT.java │ │ └── script │ │ ├── AbstractSearchScriptTestCase.java │ │ ├── NeutralFieldsTests.java │ │ ├── WeightedLevenshteinComparatorTests.java │ │ ├── EntityResolutionScriptScoreTests.java │ │ └── JaccardIndexComparatorTests.java └── main │ ├── assemblies │ └── plugin.xml │ └── java │ └── org │ └── yaba │ └── entity │ ├── plugin │ └── EntityResolutionPlugin.java │ ├── config │ └── EntityConfiguration.java │ └── script │ └── EntityResolutionScript.java ├── .gitignore ├── .gitattributes ├── dev-tools └── src │ └── main │ └── resources │ └── license-check │ ├── license-header-definition.xml │ └── entity-resolution-license-header.txt ├── README.md ├── pom.xml └── LICENSE /licenses/duke-NOTICE.txt: -------------------------------------------------------------------------------- 1 | https://github.com/larsga/duke -------------------------------------------------------------------------------- /licenses/duke-1.2.jar.sha1: -------------------------------------------------------------------------------- 1 | c570d23c3f44423dd782cfe9143bcba1ea6f303b -------------------------------------------------------------------------------- /licenses/mapdb-0.9.9.jar.sha1: -------------------------------------------------------------------------------- 1 | 3013576b4884b39321f7d4d5ac1a26e232d5f7b8 -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | branches: 3 | except: 4 | - travis 5 | sudo: false 6 | -------------------------------------------------------------------------------- /src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO, out 2 | 3 | log4j.appender.out=org.apache.log4j.ConsoleAppender 4 | log4j.appender.out.layout=org.apache.log4j.PatternLayout 5 | log4j.appender.out.layout.conversionPattern=[%d{ISO8601}][%-5p][%-25c] %m%n 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Temp and test files ignores 2 | work/ 3 | data/ 4 | logs/ 5 | build/ 6 | target/ 7 | .DS_Store 8 | *-execution-hints.log 9 | 10 | # IDEA ignores 11 | .idea/ 12 | *.iml 13 | 14 | ## eclipse ignores 15 | .project 16 | .classpath 17 | .settings 18 | */.project 19 | */.classpath 20 | */.settings 21 | */eclipse-build 22 | 23 | ## netbeans ignores 24 | nb-configuration.xml 25 | nbactions.xml 26 | -------------------------------------------------------------------------------- /src/test/resources/rest-api-spec/test/nativescript/10_test_loaded.yaml: -------------------------------------------------------------------------------- 1 | # Dummy integration tests 2 | # 3 | "entity-resolution loaded": 4 | - do: 5 | cluster.state: {} 6 | 7 | # Get master node id 8 | - set: { master_node: master } 9 | 10 | - do: 11 | nodes.info: {} 12 | 13 | - match: { nodes.$master.plugins.0.name: "elasticsearch-entity-resolution-plugin" } 14 | 15 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /dev-tools/src/main/resources/license-check/license-header-definition.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /* 5 | * 6 | */ 7 | 8 | (\s|\t)*/\*.*$ 9 | .*\*/(\s|\t)*$ 10 | false 11 | true 12 | 13 | 14 | -------------------------------------------------------------------------------- /dev-tools/src/main/resources/license-check/entity-resolution-license-header.txt: -------------------------------------------------------------------------------- 1 | Licensed under the Apache License, Version 2.0 (the "License"); 2 | you may not use this file except in compliance with the License. 3 | You may obtain a copy of the License at 4 | 5 | http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. -------------------------------------------------------------------------------- /src/main/assemblies/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | plugin 4 | 5 | zip 6 | 7 | false 8 | 9 | 10 | / 11 | true 12 | true 13 | 14 | org.elasticsearch:elasticsearch 15 | 16 | 17 | 18 | 19 | 20 | ${elasticsearch.tools.directory}/plugin-metadata/plugin-descriptor.properties 21 | 22 | true 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/main/java/org/yaba/entity/plugin/EntityResolutionPlugin.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 | 15 | package org.yaba.entity.plugin; 16 | 17 | import org.elasticsearch.plugins.Plugin; 18 | import org.elasticsearch.script.ScriptModule; 19 | import org.yaba.entity.script.EntityResolutionScript; 20 | 21 | public class EntityResolutionPlugin extends Plugin { 22 | @Override 23 | public final String name() { 24 | return "entity-resolution-plugin"; 25 | } 26 | 27 | @Override 28 | public final String description() { 29 | return "Bayesian based entity resolution plugin"; 30 | } 31 | 32 | public void onModule(ScriptModule module) { 33 | // Register each script that we defined in this plugin 34 | module.registerScript("entity-resolution", EntityResolutionScript.Factory.class); 35 | } 36 | } -------------------------------------------------------------------------------- /src/test/java/org/yaba/entity/plugin/EntityResolutionRestIT.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 org.yaba.entity.plugin; 15 | 16 | import com.carrotsearch.randomizedtesting.annotations.Name; 17 | import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; 18 | import org.elasticsearch.test.rest.ESRestTestCase; 19 | import org.elasticsearch.test.rest.RestTestCandidate; 20 | import org.elasticsearch.test.rest.parser.RestTestParseException; 21 | 22 | import java.io.IOException; 23 | 24 | public class EntityResolutionRestIT extends ESRestTestCase { 25 | 26 | public EntityResolutionRestIT(@Name("yaml") RestTestCandidate testCandidate) { 27 | super(testCandidate); 28 | } 29 | 30 | @ParametersFactory 31 | public static Iterable parameters() throws IOException, RestTestParseException { 32 | return ESRestTestCase.createParameters(0, 1); 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /src/main/java/org/yaba/entity/config/EntityConfiguration.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 | 15 | package org.yaba.entity.config; 16 | 17 | import java.util.HashMap; 18 | import java.util.Iterator; 19 | import java.util.List; 20 | import java.util.Map; 21 | 22 | public class EntityConfiguration { 23 | 24 | private Map parameters = null; 25 | 26 | public EntityConfiguration(List> params) { 27 | Iterator> it = params.iterator(); 28 | 29 | parameters = new HashMap<>(); 30 | 31 | while (it.hasNext()) { 32 | Map map = it.next(); 33 | if (!(map.get("field") == null)) { 34 | parameters.put((String) map.get("field"), map); 35 | } 36 | } 37 | } 38 | 39 | @SuppressWarnings("unchecked") 40 | public final Map getConfiguratio(String key) { 41 | return (Map) parameters.get(key); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /licenses/mapdb-NOTICE.txt: -------------------------------------------------------------------------------- 1 | MapDB 2 | Copyright 2012-2015 Jan Kotek 3 | 4 | This product includes software developed by Thomas Mueller and H2 group 5 | Relicensed under Apache License 2 with Thomas permission. 6 | (CompressLZF.java and EncryptionXTEA.java and Heartbeat file lock) 7 | Copyright (c) 2004-2011 H2 Group 8 | 9 | 10 | This product includes software developed by Doug Lea and JSR 166 group: 11 | (LongConcurrentMap.java, Atomic.java) 12 | * Written by Doug Lea with assistance from members of JCP JSR-166 13 | * Expert Group and released to the public domain, as explained at 14 | * http://creativecommons.org/licenses/publicdomain 15 | 16 | 17 | This product includes software developed for Android project 18 | (SerializerPojo, a few lines to invoke constructor, see comments) 19 | //Copyright (C) 2012 The Android Open Source Project, licenced under Apache 2 license 20 | 21 | 22 | This product includes software developed by Heinz Kabutz for javaspecialists.eu 23 | (SerializerPojo, a few lines to invoke constructor, see comments) 24 | 2010-2014 Heinz Kabutz 25 | 26 | 27 | Some Map unit tests are from Google Collections. 28 | Credit goes to Jared Levy, George van den Driessche and other Google Collections developers. 29 | Copyright (C) 2007 Google Inc. 30 | 31 | Luc Peuvrier wrote some unit tests for ConcurrentNavigableMap interface. 32 | 33 | XXHash used for char[] and byte[] hashes is from LZ4-Java 34 | (DataIO.java and UnsafeStuff.java) 35 | LZ4-Java project, Copyright (C) 2014 Adrien Grand 36 | 37 | LongObjectMap, LongLongMap and LongObjectObject map are based on Koloboke source code. 38 | (Store.java) 39 | Copyright (C) OpenHFT, Roman Leventov 40 | 41 | DataIO.longHash and DataIO.intHash are inspired by Koloboke source code 42 | (DataIO.java) 43 | Copyright (C) OpenHFT, Roman Leventov 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/YannBrrd/elasticsearch-entity-resolution.svg?branch=2.1)](http://travis-ci.org/YannBrrd/elasticsearch-entity-resolution) 2 | 3 | 4 | 5 | 6 | elasticsearch-entity-resolution 7 | =================== 8 | 9 | This project is an interactive entity resolution plugin for [Elasticsearch](http://www.elasticsearch.org) based on [Duke](http://github.com/larsga/Duke). Basically, it uses [Bayesian probabilities] (http://en.wikipedia.org/wiki/Bayesian_probability) to compute probability. You can pretty much use it as an interactive deduplication engine. 10 | 11 | To understand basics, go to [Duke project documentation](https://github.com/larsga/Duke/wiki/XMLConfig). 12 | 13 | A list of [available comparators] (https://github.com/larsga/Duke/wiki/Comparator) is available [here](https://github.com/larsga/Duke/wiki/Comparator). 14 | 15 | ### Documentation 16 | 17 | [FAQ](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/FAQ) 18 | 19 | [How to install](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/install) 20 | 21 | [Configuring the plugin](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/configure) 22 | 23 | [Caveats](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/caveats) 24 | 25 | [Going to indus mode](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/indus) 26 | 27 | [Run examples](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/Run-Examples) 28 | 29 | [Contact](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/contact) 30 | 31 | [Credits](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/credits) 32 | 33 | [What else ?](http://github.com/YannBrrd/elasticsearch-entity-resolution/wiki/what_else) 34 | 35 | 36 | ## Licence 37 | 38 | This project is licended under APL V2 39 | 40 | Copyright (c) 2014 Yann Barraud 41 | -------------------------------------------------------------------------------- /src/test/java/org/yaba/entity/script/AbstractSearchScriptTestCase.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 | 15 | package org.yaba.entity.script; 16 | 17 | import org.elasticsearch.common.settings.Settings; 18 | import org.elasticsearch.plugins.Plugin; 19 | import org.elasticsearch.test.ESIntegTestCase; 20 | import org.elasticsearch.test.ESIntegTestCase.ClusterScope; 21 | import org.elasticsearch.test.ESIntegTestCase.Scope; 22 | import org.yaba.entity.plugin.EntityResolutionPlugin; 23 | 24 | import java.util.Collection; 25 | 26 | import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; 27 | import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; 28 | 29 | /** 30 | */ 31 | @ClusterScope(scope = Scope.SUITE, numDataNodes = 1) 32 | public abstract class AbstractSearchScriptTestCase extends ESIntegTestCase { 33 | 34 | @Override 35 | public Settings indexSettings() { 36 | Settings.Builder builder = Settings.builder(); 37 | builder.put(SETTING_NUMBER_OF_SHARDS, 1); 38 | builder.put(SETTING_NUMBER_OF_REPLICAS, 0); 39 | return builder.build(); 40 | } 41 | 42 | 43 | @Override 44 | protected Collection> nodePlugins() { 45 | return pluginList(EntityResolutionPlugin.class); 46 | } 47 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | elasticsearch-entity-resolution-plugin 6 | 4.0.0 7 | 8 | 9 | org.elasticsearch.plugin 10 | plugins 11 | 2.4.2 12 | 13 | 14 | org.yaba 15 | elasticsearch-entity-resolution-plugin 16 | 2.4.2.0 17 | jar 18 | Elasticsearch Plugin for Entity Resolution 19 | 20 | 21 | YannBrrd 22 | Yann Barraud 23 | yann.barraud@gmail.com 24 | https://github.com/YannBrrd 25 | 26 | architect 27 | developer 28 | 29 | +1 30 | 31 | 32 | 2014 33 | 34 | 35 | The Apache Software License, Version 2.0 36 | http://www.apache.org/licenses/LICENSE-2.0.txt 37 | repo 38 | 39 | 40 | 41 | scm:git:git@github.com:YannBrrd/elasticsearch-entity-resolution.git 42 | scm:git:git@github.com:YannBrrd/elasticsearch-entity-resolution.git 43 | http://github.com/YannBrrd/elasticsearch-entity-resolution 44 | 45 | 46 | 47 | 48 | org.yaba.entity.plugin.EntityResolutionPlugin 49 | ${project.basedir}/src/main/assemblies/plugin-assembly.xml 50 | 51 | 2.4.2 52 | false 53 | true 54 | 55 | 56 | 57 | file:///${project.basedir}/dev-tools/src/main/resources/license-check/entity-resolution-license-header.txt 58 | 59 | 60 | file:///${project.basedir}/dev-tools/src/main/resources/license-check/license-header-definition.xml 61 | 62 | 63 | 64 | warn 65 | nativescript 66 | false 67 | UTF-8 68 | 1.2 69 | 70 | 71 | 72 | 73 | bintray-yann-barraud-elasticsearch-entity-resolution-elasticsearch-entity-resolution 74 | yann-barraud-elasticsearch-entity-resolution-elasticsearch-entity-resolution 75 | 76 | https://api.bintray.com/maven/yann-barraud/elasticsearch-entity-resolution/elasticsearch-entity-resolution 77 | 78 | 79 | 80 | 81 | 82 | 83 | no.priv.garshol.duke 84 | duke 85 | ${duke.version} 86 | 87 | 88 | 89 | 90 | 91 | oss-snapshots 92 | Sonatype OSS Snapshots 93 | https://oss.sonatype.org/content/repositories/snapshots/ 94 | 95 | 96 | 97 | 98 | 99 | 100 | org.apache.maven.plugins 101 | maven-assembly-plugin 102 | 103 | 104 | ${project.basedir}/src/main/assemblies/plugin.xml 105 | 106 | 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /src/test/java/org/yaba/entity/script/NeutralFieldsTests.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 | 15 | package org.yaba.entity.script; 16 | 17 | import org.elasticsearch.action.index.IndexRequestBuilder; 18 | import org.elasticsearch.action.search.SearchRequestBuilder; 19 | import org.elasticsearch.action.search.SearchResponse; 20 | import org.elasticsearch.common.collect.MapBuilder; 21 | import org.elasticsearch.common.lucene.search.function.CombineFunction; 22 | import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; 23 | import org.elasticsearch.script.Script; 24 | import org.elasticsearch.script.ScriptService; 25 | import org.junit.Test; 26 | 27 | import java.io.IOException; 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.Map; 32 | import java.util.concurrent.ExecutionException; 33 | 34 | import static java.lang.Float.valueOf; 35 | import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; 36 | import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; 37 | import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; 38 | import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; 39 | import static org.hamcrest.Matchers.equalTo; 40 | 41 | public class NeutralFieldsTests extends AbstractSearchScriptTestCase { 42 | @Test 43 | public final void testEntity() throws IOException, ExecutionException, InterruptedException { 44 | 45 | 46 | // Create a new test index 47 | String testMapping = 48 | jsonBuilder() 49 | .startObject() 50 | .startObject("user") 51 | .startObject("_timestamp") 52 | .field("enabled", false) 53 | .endObject() 54 | .startObject("properties") 55 | .startObject("gender") 56 | .field("type", "string") 57 | .field("index", "not_analyzed") 58 | .endObject() 59 | .startObject("name") 60 | .field("type", "string") 61 | .field("index", "not_analyzed") 62 | .endObject() 63 | .endObject() 64 | .endObject() 65 | .string(); 66 | 67 | assertAcked(prepareCreate("test").addMapping("user", testMapping)); 68 | 69 | List indexBuilders = new ArrayList<>(); 70 | 71 | // Index main records 72 | indexBuilders.add(client() 73 | .prepareIndex("test", "user", "1") 74 | .setSource("name", "dale", "gender", "m")); 75 | indexBuilders.add(client() 76 | .prepareIndex("test", "user", "2") 77 | .setSource("name", "david")); 78 | indexBuilders.add(client() 79 | .prepareIndex("test", "user", "3") 80 | .setSource("name", "dale")); 81 | 82 | indexRandom(true, indexBuilders); 83 | 84 | // Script parameters 85 | Map params = 86 | MapBuilder.newMapBuilder().map(); 87 | 88 | ArrayList> fields; 89 | fields = new ArrayList<>(); 90 | 91 | Map aField = 92 | MapBuilder 93 | .newMapBuilder() 94 | .put("field", "name") 95 | .put("value", "dale") 96 | .put("comparator", MapBuilder.newMapBuilder() 97 | .put("name", "no.priv.garshol.duke.comparators.ExactComparator") 98 | .map()) 99 | .put("low", 0.1) 100 | .put("high", 0.9) 101 | .put("cleaners", new Map[]{ 102 | MapBuilder.newMapBuilder() 103 | .put("name", "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 104 | .map()}) 105 | .map(); 106 | 107 | fields.add(aField); 108 | 109 | aField = 110 | MapBuilder 111 | .newMapBuilder() 112 | .put("field", "gender") 113 | .put("value", "m") 114 | .put("comparator", MapBuilder.newMapBuilder() 115 | .put("name", "no.priv.garshol.duke.comparators.ExactComparator") 116 | .map()) 117 | .put("low", 0.0) 118 | .put("high", 0.9) 119 | .put("cleaners", new Map[]{ 120 | MapBuilder.newMapBuilder() 121 | .put("name", "no.priv.garshol.duke.cleaners.TrimCleaner") 122 | .map(), 123 | MapBuilder.newMapBuilder() 124 | .put("name", "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 125 | .map()}) 126 | .map(); 127 | 128 | fields.add(aField); 129 | 130 | params.put( 131 | "entity", 132 | new MapBuilder>>().put( 133 | "fields", fields).map()); 134 | 135 | // Find all objects 136 | SearchRequestBuilder request = 137 | client() 138 | .prepareSearch("test") 139 | .setTypes("user") 140 | .setQuery( 141 | functionScoreQuery( 142 | (matchAllQuery())) 143 | .boostMode(CombineFunction.REPLACE) 144 | .scoreMode("max") 145 | .add(ScoreFunctionBuilders.scriptFunction(new Script(EntityResolutionScript.SCRIPT_NAME, ScriptService.ScriptType.INLINE, "native", params)))) 146 | .setSize(4); 147 | 148 | logger.info(request.toString()); 149 | 150 | SearchResponse searchResponse = request.execute().actionGet(); 151 | 152 | assertThat(Arrays.toString(searchResponse.getShardFailures()), 153 | searchResponse.getFailedShards(), equalTo(0)); 154 | 155 | logger.info(searchResponse.toString()); 156 | 157 | assertThat(searchResponse.getHits().getAt(0).getSource().get("name") 158 | .toString(), equalTo("dale")); 159 | assertThat(searchResponse.getHits().getAt(0).getScore(), equalTo( 160 | valueOf("0.9878049"))); 161 | 162 | assertThat(searchResponse.getHits().getAt(1).getSource().get("name") 163 | .toString(), equalTo("dale")); 164 | assertThat(searchResponse.getHits().getAt(1).getScore(), equalTo( 165 | valueOf("0.9"))); 166 | 167 | assertThat(searchResponse.getHits().getAt(2).getSource().get("name") 168 | .toString(), equalTo("david")); 169 | assertThat(searchResponse.getHits().getAt(2).getScore(), equalTo( 170 | valueOf("0.1"))); 171 | 172 | 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /licenses/duke-LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "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. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "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. 22 | 23 | "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). 24 | 25 | "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. 26 | 27 | "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." 28 | 29 | "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. 30 | 31 | 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. 32 | 33 | 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. 34 | 35 | 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: 36 | 37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | You must cause any modified files to carry prominent notices stating that You changed the files; and 39 | 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 40 | 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. 41 | 42 | 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. 43 | 44 | 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. 45 | 46 | 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. 47 | 48 | 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. 49 | 50 | 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. 51 | 52 | 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. 53 | 54 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /licenses/mapdb-LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /src/test/java/org/yaba/entity/script/WeightedLevenshteinComparatorTests.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 | 15 | package org.yaba.entity.script; 16 | 17 | import org.elasticsearch.action.index.IndexRequestBuilder; 18 | import org.elasticsearch.action.search.SearchRequestBuilder; 19 | import org.elasticsearch.action.search.SearchResponse; 20 | import org.elasticsearch.common.collect.MapBuilder; 21 | import org.elasticsearch.common.lucene.search.function.CombineFunction; 22 | import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; 23 | import org.elasticsearch.script.Script; 24 | import org.elasticsearch.script.ScriptService; 25 | import org.junit.Test; 26 | 27 | import java.io.IOException; 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.Map; 32 | import java.util.concurrent.ExecutionException; 33 | 34 | import static java.lang.Float.valueOf; 35 | import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; 36 | import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; 37 | import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; 38 | import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; 39 | import static org.hamcrest.Matchers.equalTo; 40 | 41 | public class WeightedLevenshteinComparatorTests extends AbstractSearchScriptTestCase { 42 | 43 | public static final String CITY = "city"; 44 | public static final String PROPERTIES = "properties"; 45 | public static final String TYPE = "type"; 46 | public static final String STRING = "string"; 47 | public static final String STATE = "state"; 48 | public static final String INDEX = "index"; 49 | public static final String NOT_ANALYZED = "not_analyzed"; 50 | public static final String POPULATION = "population"; 51 | public static final String INTEGER = "integer"; 52 | public static final String POSITION = "position"; 53 | public static final String GEO_POINT = "geo_point"; 54 | public static final String TEST = "test"; 55 | public static final String FIELD = "field"; 56 | public static final String VALUE = "value"; 57 | public static final String COMPARATOR = "comparator"; 58 | public static final String NAME = "name"; 59 | public static final String LOW = "low"; 60 | public static final String HIGH = "high"; 61 | public static final String CLEANERS = "cleaners"; 62 | public static final String ADDRESS = "address"; 63 | public static final String ZIP = "zip"; 64 | public static final String EMAIL = "email"; 65 | public static final String PERSON = "person"; 66 | public static final String PARAMS = "params"; 67 | public static final String OBJECT = "object"; 68 | 69 | 70 | @Test 71 | public final void testEntity() throws IOException, ExecutionException, InterruptedException { 72 | 73 | String testMapping = 74 | jsonBuilder() 75 | .startObject() 76 | .startObject(PERSON) 77 | .startObject(PROPERTIES) 78 | .startObject(NAME) 79 | .field(TYPE,STRING) 80 | .field(INDEX,NOT_ANALYZED) 81 | .endObject() 82 | .startObject(ADDRESS) 83 | .field(TYPE,STRING) 84 | .field(INDEX,NOT_ANALYZED) 85 | .endObject() 86 | .startObject(ZIP) 87 | .field(TYPE,INTEGER) 88 | .field(INDEX,NOT_ANALYZED) 89 | .endObject() 90 | .startObject(EMAIL) 91 | .field(TYPE,STRING) 92 | .endObject() 93 | .endObject() 94 | .endObject() 95 | .endObject() 96 | .string(); 97 | System.out.println(testMapping); 98 | assertAcked(prepareCreate(TEST).addMapping(PERSON, testMapping)); 99 | 100 | List indexBuilders = new ArrayList<>(); 101 | 102 | indexBuilders.add(client() 103 | .prepareIndex(TEST,PERSON,"1") 104 | .setSource(NAME,"J. Random Hacker",ADDRESS,"Main St 101", ZIP,"21231")); 105 | indexBuilders.add(client() 106 | .prepareIndex(TEST,PERSON,"2") 107 | .setSource(NAME,"John Random Hacker",ADDRESS,"Mian Street 101",ZIP,"21231",EMAIL,"hack@gmail.com")); 108 | indexBuilders.add(client() 109 | .prepareIndex(TEST,PERSON,"3") 110 | .setSource(NAME,"Jacob Hacker",ADDRESS,"Main Street 201",ZIP,"38122",EMAIL,"jacob@hotmail.com")); 111 | indexBuilders.add(client() 112 | .prepareIndex(TEST,PERSON,"4") 113 | .setSource(NAME,"J Random Hacker",ADDRESS,"Main St 101",ZIP,"21231")); 114 | indexRandom(true, indexBuilders); 115 | 116 | // Script parameters 117 | Map params = 118 | MapBuilder.newMapBuilder().map(); 119 | 120 | ArrayList> fields; 121 | fields = new ArrayList<>(); 122 | 123 | Map aField = 124 | MapBuilder 125 | .newMapBuilder() 126 | .put(FIELD, ADDRESS) 127 | .put(VALUE, "Main Street 101") 128 | .put(COMPARATOR, MapBuilder.newMapBuilder() 129 | .put(NAME, "no.priv.garshol.duke.comparators.WeightedLevenshtein") 130 | .put(PARAMS, MapBuilder.newMapBuilder() 131 | .put("digit-weight", "4.0") 132 | .put("letter-weight", "1.3") 133 | .put("punctuation-weight", "10.3") 134 | .map()) 135 | .map()) 136 | .put(LOW, 0.1) 137 | .put(HIGH, 0.95) 138 | .put(CLEANERS, new Map[]{ 139 | MapBuilder.newMapBuilder() 140 | .put(NAME, "no.priv.garshol.duke.cleaners.TrimCleaner") 141 | .map(), 142 | MapBuilder.newMapBuilder() 143 | .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 144 | .map()}) 145 | .map(); 146 | 147 | fields.add(aField); 148 | 149 | // aField = 150 | // MapBuilder 151 | // .newMapBuilder() 152 | // .put(FIELD, NAME) 153 | // .put(VALUE, "Random") 154 | // .put(COMPARATOR, MapBuilder.newMapBuilder() 155 | // .put(NAME, "no.priv.garshol.duke.comparators.QGramComparator") 156 | // .map()) 157 | // 158 | // .put(LOW, 0.35) 159 | // .put(HIGH, 0.88) 160 | // .put(CLEANERS, new Map[]{ 161 | // MapBuilder.newMapBuilder() 162 | // .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 163 | // .map()}) 164 | // .map(); 165 | // 166 | // fields.add(aField); 167 | // 168 | // aField = 169 | // MapBuilder 170 | // .newMapBuilder() 171 | // .put(FIELD, ADDRESS) 172 | // .put(COMPARATOR, MapBuilder.newMapBuilder() 173 | // .put(NAME,"no.priv.garshol.duke.comparators.ExactComparator") 174 | // .map()) 175 | // .put(LOW, 0.4) 176 | // .put(HIGH, 0.8) 177 | // .map(); 178 | // fields.add(aField); 179 | 180 | params.put( 181 | "entity", 182 | new MapBuilder>>().put( 183 | "fields", fields).map()); 184 | 185 | // Find all objects 186 | SearchRequestBuilder request = 187 | client() 188 | .prepareSearch(TEST) 189 | .setTypes(PERSON) 190 | .setQuery( 191 | functionScoreQuery( 192 | (matchAllQuery())) 193 | .boostMode(CombineFunction.REPLACE.getName()) 194 | .scoreMode("max") 195 | .add(ScoreFunctionBuilders.scriptFunction(new Script(EntityResolutionScript.SCRIPT_NAME, ScriptService.ScriptType.INLINE, "native", params)))) 196 | .setSize(4); 197 | 198 | 199 | 200 | logger.info("\n" + request.toString()); 201 | 202 | 203 | SearchResponse searchResponse = request.execute().actionGet(); 204 | 205 | assertThat(Arrays.toString(searchResponse.getShardFailures()), 206 | searchResponse.getFailedShards(), equalTo(0)); 207 | 208 | logger.info(searchResponse.toString()); 209 | 210 | assertThat(searchResponse.getHits().getAt(0).getSource().get(ADDRESS).toString(), equalTo("Mian Street 101")); 211 | assertThat(searchResponse.getHits().getAt(0).getScore(),equalTo(valueOf("0.80752"))); 212 | 213 | assertThat(searchResponse.getHits().getAt(1).getSource().get(NAME).toString(), 214 | equalTo("Jacob Hacker")); 215 | assertThat(searchResponse.getHits().getAt(1).getScore(), 216 | equalTo(valueOf("0.742"))); 217 | 218 | assertThat(searchResponse.getHits().getAt(2).getScore(), 219 | equalTo(valueOf("0.62510747"))); 220 | assertThat(searchResponse.getHits().getAt(3).getScore(), 221 | equalTo(valueOf("0.62510747"))); 222 | } 223 | } -------------------------------------------------------------------------------- /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 2015} Yann Barraud 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. -------------------------------------------------------------------------------- /src/test/java/org/yaba/entity/script/EntityResolutionScriptScoreTests.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 | 15 | package org.yaba.entity.script; 16 | 17 | import org.elasticsearch.action.index.IndexRequestBuilder; 18 | import org.elasticsearch.action.search.SearchRequestBuilder; 19 | import org.elasticsearch.action.search.SearchResponse; 20 | import org.elasticsearch.common.collect.MapBuilder; 21 | import org.elasticsearch.common.lucene.search.function.CombineFunction; 22 | import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; 23 | import org.elasticsearch.script.Script; 24 | import org.elasticsearch.script.ScriptService; 25 | import org.junit.Test; 26 | 27 | import java.io.IOException; 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.Map; 32 | import java.util.concurrent.ExecutionException; 33 | 34 | import static java.lang.Float.valueOf; 35 | import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; 36 | import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; 37 | import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; 38 | import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; 39 | import static org.hamcrest.Matchers.equalTo; 40 | 41 | public class EntityResolutionScriptScoreTests extends AbstractSearchScriptTestCase { 42 | 43 | public static final String CITY = "city"; 44 | public static final String PROPERTIES = "properties"; 45 | public static final String TYPE = "type"; 46 | public static final String STRING = "string"; 47 | public static final String STATE = "state"; 48 | public static final String INDEX = "index"; 49 | public static final String NOT_ANALYZED = "not_analyzed"; 50 | public static final String POPULATION = "population"; 51 | public static final String INTEGER = "integer"; 52 | public static final String POSITION = "position"; 53 | public static final String GEO_POINT = "geo_point"; 54 | public static final String TEST = "test"; 55 | public static final String FIELD = "field"; 56 | public static final String VALUE = "value"; 57 | public static final String COMPARATOR = "comparator"; 58 | public static final String NAME = "name"; 59 | public static final String LOW = "low"; 60 | public static final String HIGH = "high"; 61 | public static final String CLEANERS = "cleaners"; 62 | 63 | @Test 64 | public final void testEntity() throws IOException, ExecutionException, InterruptedException { 65 | 66 | 67 | // Create a new test index 68 | String testMapping = 69 | jsonBuilder() 70 | .startObject() 71 | .startObject(CITY) 72 | .startObject(PROPERTIES) 73 | .startObject(CITY) 74 | .field(TYPE, STRING) 75 | .endObject() 76 | .startObject(STATE) 77 | .field(TYPE, STRING) 78 | .field(INDEX, NOT_ANALYZED) 79 | .endObject() 80 | .startObject(POPULATION) 81 | .field(TYPE, INTEGER) 82 | .endObject() 83 | .startObject(POSITION) 84 | .field(TYPE, GEO_POINT) 85 | .endObject() 86 | .endObject() 87 | .endObject() 88 | .endObject() 89 | .string(); 90 | 91 | assertAcked(prepareCreate(TEST).addMapping(CITY, testMapping)); 92 | 93 | List indexBuilders = new ArrayList<>(); 94 | 95 | // Index main records 96 | indexBuilders.add(client() 97 | .prepareIndex(TEST, CITY, "1") 98 | .setSource(CITY, "Cambridge", STATE, "MA", POPULATION, 99 | 105162, POSITION, "42.373746,71.110554")); 100 | indexBuilders.add(client() 101 | .prepareIndex(TEST, CITY, "2") 102 | .setSource(CITY, "South Burlington", STATE, "VT", 103 | POPULATION, 17904, POSITION, "44.451846,73.181710")); 104 | indexBuilders.add(client() 105 | .prepareIndex(TEST, CITY, "3") 106 | .setSource(CITY, "South Portland", STATE, "ME", 107 | POPULATION, 25002, POSITION, "43.631549,70.272724")); 108 | indexBuilders.add(client().prepareIndex(TEST, CITY, "4") 109 | .setSource(CITY, "Essex", STATE, "VT", POPULATION, 19587, POSITION, "44.492905,73.108601") 110 | ); 111 | indexBuilders.add(client() 112 | .prepareIndex(TEST, CITY, "5") 113 | .setSource(CITY, "Portland", STATE, "ME", POPULATION, 114 | 66194, POSITION, "43.665116,70.269086")); 115 | indexBuilders.add(client() 116 | .prepareIndex(TEST, CITY, "6") 117 | .setSource(CITY, "Burlington", STATE, "VT", POPULATION, 118 | 42417, POSITION, "44.484748,73.223157")); 119 | indexBuilders.add(client() 120 | .prepareIndex(TEST, CITY, "7") 121 | .setSource(CITY, "Stamford", STATE, "CT", POPULATION, 122 | 122643, POSITION, "41.074448,73.541316")); 123 | indexBuilders.add(client() 124 | .prepareIndex(TEST, CITY, "8") 125 | .setSource(CITY, "Colchester", STATE, "VT", POPULATION, 126 | 17067, POSITION, "44.3231,73.148")); 127 | indexBuilders.add(client() 128 | .prepareIndex(TEST, CITY, "9") 129 | .setSource(CITY, "Concord", STATE, "NH", POPULATION, 130 | 42695, POSITION, "43.220093,71.549127")); 131 | indexBuilders.add(client() 132 | .prepareIndex(TEST, CITY, "10") 133 | .setSource(CITY, "Boston", STATE, "MA", POPULATION, 134 | 617594, POSITION, "42.321597,71.089115")); 135 | 136 | indexRandom(true, indexBuilders); 137 | 138 | // Script parameters 139 | Map params = 140 | MapBuilder.newMapBuilder().map(); 141 | 142 | ArrayList> fields; 143 | fields = new ArrayList<>(); 144 | 145 | Map aField = 146 | MapBuilder 147 | .newMapBuilder() 148 | .put(FIELD, CITY) 149 | .put(VALUE, "South") 150 | .put(COMPARATOR, MapBuilder.newMapBuilder() 151 | .put(NAME, "no.priv.garshol.duke.comparators.JaroWinkler") 152 | .map()) 153 | .put(LOW, 0.1) 154 | .put(HIGH, 0.95) 155 | .put(CLEANERS, new Map[]{ 156 | MapBuilder.newMapBuilder() 157 | .put(NAME, "no.priv.garshol.duke.cleaners.TrimCleaner") 158 | .map(), 159 | MapBuilder.newMapBuilder() 160 | .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 161 | .map()}) 162 | .map(); 163 | 164 | fields.add(aField); 165 | 166 | aField = 167 | MapBuilder 168 | .newMapBuilder() 169 | .put(FIELD, STATE) 170 | .put(VALUE, "ME") 171 | .put(COMPARATOR, MapBuilder.newMapBuilder() 172 | .put(NAME, "no.priv.garshol.duke.comparators.JaroWinkler") 173 | .map()) 174 | .put(LOW, 0.1) 175 | .put(HIGH, 0.95) 176 | .put(CLEANERS, new Map[]{ 177 | MapBuilder.newMapBuilder() 178 | .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 179 | .map()}) 180 | .map(); 181 | 182 | fields.add(aField); 183 | 184 | aField = 185 | MapBuilder 186 | .newMapBuilder() 187 | .put(FIELD, POPULATION) 188 | .put(VALUE, "26000") 189 | .put(COMPARATOR, MapBuilder.newMapBuilder() 190 | .put(NAME, "no.priv.garshol.duke.comparators.NumericComparator") 191 | .map()) 192 | .put(LOW, 0.1) 193 | .put(HIGH, 0.95) 194 | .put(CLEANERS, new Map[]{ 195 | MapBuilder.newMapBuilder() 196 | .put(NAME, "no.priv.garshol.duke.cleaners.DigitsOnlyCleaner") 197 | .map()}) 198 | .map(); 199 | 200 | fields.add(aField); 201 | 202 | aField = 203 | MapBuilder 204 | .newMapBuilder() 205 | .put(FIELD, POSITION) 206 | .put(VALUE, "43,70") 207 | .put(COMPARATOR, MapBuilder.newMapBuilder() 208 | .put(NAME, "no.priv.garshol.duke.comparators.GeopositionComparator") 209 | .put("params", MapBuilder.newMapBuilder() 210 | .put("max-distance", "100").map() 211 | ).map()) 212 | .put(LOW, 0.1) 213 | .put(HIGH, 0.95) 214 | .put(CLEANERS, new Map[]{ 215 | MapBuilder.newMapBuilder() 216 | .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 217 | .map()}) 218 | .map(); 219 | 220 | fields.add(aField); 221 | 222 | params.put( 223 | "entity", 224 | new MapBuilder>>().put( 225 | "fields", fields).map()); 226 | 227 | // Find all objects 228 | SearchRequestBuilder request = 229 | client() 230 | .prepareSearch(TEST) 231 | .setTypes(CITY) 232 | .setQuery( 233 | functionScoreQuery( 234 | (matchAllQuery())) 235 | .boostMode(CombineFunction.REPLACE.getName()) 236 | .scoreMode("max") 237 | .add(ScoreFunctionBuilders.scriptFunction(new Script(EntityResolutionScript.SCRIPT_NAME, ScriptService.ScriptType.INLINE, "native", params)))) 238 | .setSize(4); 239 | 240 | 241 | 242 | logger.info("\n" + request.toString()); 243 | 244 | 245 | SearchResponse searchResponse = request.execute().actionGet(); 246 | 247 | assertThat(Arrays.toString(searchResponse.getShardFailures()), 248 | searchResponse.getFailedShards(), equalTo(0)); 249 | 250 | logger.info(searchResponse.toString()); 251 | 252 | assertThat(searchResponse.getHits().getAt(0).getSource().get(CITY) 253 | .toString(), equalTo("South Portland")); 254 | assertThat(searchResponse.getHits().getAt(0).getScore(), equalTo( 255 | valueOf("0.97579086"))); 256 | 257 | assertThat(searchResponse.getHits().getAt(1).getSource().get(CITY) 258 | .toString(), equalTo("Portland")); 259 | assertThat(searchResponse.getHits().getAt(1).getScore(), equalTo( 260 | valueOf("0.29081574"))); 261 | 262 | assertThat(searchResponse.getHits().getAt(2).getSource().get(CITY) 263 | .toString(), equalTo("Boston")); 264 | assertThat(searchResponse.getHits().getAt(2).getScore(), equalTo( 265 | valueOf("0.057230186"))); 266 | 267 | assertThat(searchResponse.getHits().getAt(3).getSource().get(CITY) 268 | .toString(), equalTo("South Burlington")); 269 | assertThat(searchResponse.getHits().getAt(3).getScore(), equalTo( 270 | valueOf("0.049316783"))); 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/test/java/org/yaba/entity/script/JaccardIndexComparatorTests.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 | 15 | package org.yaba.entity.script; 16 | 17 | import org.elasticsearch.action.index.IndexRequestBuilder; 18 | import org.elasticsearch.action.search.SearchRequestBuilder; 19 | import org.elasticsearch.action.search.SearchResponse; 20 | import org.elasticsearch.common.collect.MapBuilder; 21 | import org.elasticsearch.common.lucene.search.function.CombineFunction; 22 | import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; 23 | import org.elasticsearch.script.Script; 24 | import org.elasticsearch.script.ScriptService; 25 | import org.junit.Test; 26 | 27 | import java.io.IOException; 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.Map; 32 | import java.util.concurrent.ExecutionException; 33 | 34 | import static java.lang.Float.valueOf; 35 | import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; 36 | import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; 37 | import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; 38 | import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; 39 | import static org.hamcrest.Matchers.equalTo; 40 | 41 | public class JaccardIndexComparatorTests extends AbstractSearchScriptTestCase { 42 | 43 | 44 | public static final String CITY = "city"; 45 | public static final String PROPERTIES = "properties"; 46 | public static final String TYPE = "type"; 47 | public static final String STRING = "string"; 48 | public static final String STATE = "state"; 49 | public static final String INDEX = "index"; 50 | public static final String NOT_ANALYZED = "not_analyzed"; 51 | public static final String POPULATION = "population"; 52 | public static final String INTEGER = "integer"; 53 | public static final String POSITION = "position"; 54 | public static final String GEO_POINT = "geo_point"; 55 | public static final String TEST = "test"; 56 | public static final String FIELD = "field"; 57 | public static final String VALUE = "value"; 58 | public static final String COMPARATOR = "comparator"; 59 | public static final String NAME = "name"; 60 | public static final String LOW = "low"; 61 | public static final String HIGH = "high"; 62 | public static final String CLEANERS = "cleaners"; 63 | 64 | @Test 65 | public final void testEntity() throws IOException, ExecutionException, InterruptedException { 66 | 67 | 68 | // Create a new test index 69 | String testMapping = 70 | jsonBuilder() 71 | .startObject() 72 | .startObject(CITY) 73 | .startObject(PROPERTIES) 74 | .startObject(CITY) 75 | .field(TYPE, STRING) 76 | .endObject() 77 | .startObject(STATE) 78 | .field(TYPE, STRING) 79 | .field(INDEX, NOT_ANALYZED) 80 | .endObject() 81 | .startObject(POPULATION) 82 | .field(TYPE, INTEGER) 83 | .endObject() 84 | .startObject(POSITION) 85 | .field(TYPE, GEO_POINT) 86 | .endObject() 87 | .endObject() 88 | .endObject() 89 | .endObject() 90 | .string(); 91 | 92 | assertAcked(prepareCreate(TEST).addMapping(CITY, testMapping)); 93 | 94 | List indexBuilders = new ArrayList<>(); 95 | 96 | // Index main records 97 | indexBuilders.add(client() 98 | .prepareIndex(TEST, CITY, "1") 99 | .setSource(CITY, "Cambridge", STATE, "MA", POPULATION, 100 | 105162, POSITION, "42.373746,71.110554")); 101 | indexBuilders.add(client() 102 | .prepareIndex(TEST, CITY, "2") 103 | .setSource(CITY, "South Burlington", STATE, "VT", 104 | POPULATION, 17904, POSITION, "44.451846,73.181710")); 105 | indexBuilders.add(client() 106 | .prepareIndex(TEST, CITY, "3") 107 | .setSource(CITY, "South Portland", STATE, "ME", 108 | POPULATION, 25002, POSITION, "43.631549,70.272724")); 109 | indexBuilders.add(client().prepareIndex(TEST, CITY, "4") 110 | .setSource(CITY, "Essex", STATE, "VT", POPULATION, 19587, POSITION, "44.492905,73.108601") 111 | ); 112 | indexBuilders.add(client() 113 | .prepareIndex(TEST, CITY, "5") 114 | .setSource(CITY, "Portland", STATE, "ME", POPULATION, 115 | 66194, POSITION, "43.665116,70.269086")); 116 | indexBuilders.add(client() 117 | .prepareIndex(TEST, CITY, "6") 118 | .setSource(CITY, "Burlington", STATE, "VT", POPULATION, 119 | 42417, POSITION, "44.484748,73.223157")); 120 | indexBuilders.add(client() 121 | .prepareIndex(TEST, CITY, "7") 122 | .setSource(CITY, "Stamford", STATE, "CT", POPULATION, 123 | 122643, POSITION, "41.074448,73.541316")); 124 | indexBuilders.add(client() 125 | .prepareIndex(TEST, CITY, "8") 126 | .setSource(CITY, "Colchester", STATE, "VT", POPULATION, 127 | 17067, POSITION, "44.3231,73.148")); 128 | indexBuilders.add(client() 129 | .prepareIndex(TEST, CITY, "9") 130 | .setSource(CITY, "Concord", STATE, "NH", POPULATION, 131 | 42695, POSITION, "43.220093,71.549127")); 132 | indexBuilders.add(client() 133 | .prepareIndex(TEST, CITY, "10") 134 | .setSource(CITY, "Boston", STATE, "MA", POPULATION, 135 | 617594, POSITION, "42.321597,71.089115")); 136 | 137 | indexRandom(true, indexBuilders); 138 | 139 | // Script parameters 140 | Map params = 141 | MapBuilder.newMapBuilder().map(); 142 | 143 | ArrayList> fields; 144 | fields = new ArrayList<>(); 145 | 146 | Map aField = 147 | MapBuilder 148 | .newMapBuilder() 149 | .put(FIELD, CITY) 150 | .put(VALUE, "South") 151 | .put(COMPARATOR, MapBuilder.newMapBuilder() 152 | .put(NAME, "no.priv.garshol.duke.comparators.JaccardIndexComparator") 153 | .put("objects", MapBuilder.newMapBuilder() 154 | .put("object", MapBuilder.newMapBuilder() 155 | .put("class", "no.priv.garshol.duke.comparators.Levenshtein") 156 | .put("name", "comparator") 157 | .map()) 158 | .map()) 159 | .map()) 160 | .put(LOW, 0.1) 161 | .put(HIGH, 0.95) 162 | .put(CLEANERS, new Map[]{ 163 | MapBuilder.newMapBuilder() 164 | .put(NAME, "no.priv.garshol.duke.cleaners.TrimCleaner") 165 | .map(), 166 | MapBuilder.newMapBuilder() 167 | .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 168 | .map()}) 169 | .map(); 170 | 171 | fields.add(aField); 172 | 173 | aField = 174 | MapBuilder 175 | .newMapBuilder() 176 | .put(FIELD, STATE) 177 | .put(VALUE, "ME") 178 | .put(COMPARATOR, MapBuilder.newMapBuilder() 179 | .put(NAME, "no.priv.garshol.duke.comparators.JaroWinkler") 180 | .map()) 181 | 182 | .put(LOW, 0.1) 183 | .put(HIGH, 0.95) 184 | .put(CLEANERS, new Map[]{ 185 | MapBuilder.newMapBuilder() 186 | .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 187 | .map()}) 188 | .map(); 189 | 190 | fields.add(aField); 191 | 192 | aField = 193 | MapBuilder 194 | .newMapBuilder() 195 | .put(FIELD, POPULATION) 196 | .put(VALUE, "26000") 197 | .put(COMPARATOR, MapBuilder.newMapBuilder() 198 | .put(NAME, "no.priv.garshol.duke.comparators.NumericComparator") 199 | .map()) 200 | .put(LOW, 0.1) 201 | .put(HIGH, 0.95) 202 | .put(CLEANERS, new Map[]{ 203 | MapBuilder.newMapBuilder() 204 | .put(NAME, "no.priv.garshol.duke.cleaners.DigitsOnlyCleaner") 205 | .map()}) 206 | .map(); 207 | 208 | fields.add(aField); 209 | 210 | aField = 211 | MapBuilder 212 | .newMapBuilder() 213 | .put(FIELD, POSITION) 214 | .put(VALUE, "43,70") 215 | .put(COMPARATOR, MapBuilder.newMapBuilder() 216 | .put(NAME, "no.priv.garshol.duke.comparators.GeopositionComparator") 217 | .put("params", MapBuilder.newMapBuilder() 218 | .put("max-distance", "100").map() 219 | ).map()) 220 | .put(LOW, 0.1) 221 | .put(HIGH, 0.95) 222 | .put(CLEANERS, new Map[]{ 223 | MapBuilder.newMapBuilder() 224 | .put(NAME, "no.priv.garshol.duke.cleaners.LowerCaseNormalizeCleaner") 225 | .map()}) 226 | .map(); 227 | 228 | fields.add(aField); 229 | 230 | params.put( 231 | "entity", 232 | new MapBuilder>>().put( 233 | "fields", fields).map()); 234 | 235 | // Find all objects 236 | SearchRequestBuilder request = 237 | client() 238 | .prepareSearch(TEST) 239 | .setTypes(CITY) 240 | .setQuery( 241 | functionScoreQuery( 242 | (matchAllQuery())) 243 | .boostMode(CombineFunction.REPLACE) 244 | .scoreMode("max") 245 | .add(ScoreFunctionBuilders.scriptFunction(new Script(EntityResolutionScript.SCRIPT_NAME, ScriptService.ScriptType.INLINE, "native", params)))) 246 | .setSize(4); 247 | 248 | logger.info(request.toString()); 249 | 250 | SearchResponse searchResponse = request.execute().actionGet(); 251 | 252 | assertThat(Arrays.toString(searchResponse.getShardFailures()), 253 | searchResponse.getFailedShards(), equalTo(0)); 254 | 255 | logger.info(searchResponse.toString()); 256 | 257 | assertThat(searchResponse.getHits().getAt(0).getSource().get(CITY) 258 | .toString(), equalTo("South Portland")); 259 | assertThat(searchResponse.getHits().getAt(0).getScore(), equalTo( 260 | valueOf("0.7192429"))); 261 | 262 | assertThat(searchResponse.getHits().getAt(1).getSource().get(CITY) 263 | .toString(), equalTo("Portland")); 264 | assertThat(searchResponse.getHits().getAt(1).getScore(), equalTo( 265 | valueOf("0.025401069"))); 266 | 267 | assertThat(searchResponse.getHits().getAt(2).getSource().get(CITY) 268 | .toString(), equalTo("Essex")); 269 | assertThat(searchResponse.getHits().getAt(2).getScore(), equalTo( 270 | valueOf("0.0042182333"))); 271 | 272 | 273 | /* 274 | TODO : Need to check and fix this test 275 | 276 | assertThat(searchResponse.getHits().getAt(3).getSource().get(CITY) 277 | 278 | .toString(), equalTo("Boston")); 279 | assertThat(searchResponse.getHits().getAt(3).getScore(), equalTo( 280 | valueOf("0.0035236408"))); */ 281 | 282 | } 283 | 284 | } 285 | -------------------------------------------------------------------------------- /src/main/java/org/yaba/entity/script/EntityResolutionScript.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 | 15 | package org.yaba.entity.script; 16 | 17 | import com.google.common.cache.Cache; 18 | import com.google.common.cache.CacheBuilder; 19 | import no.priv.garshol.duke.Cleaner; 20 | import no.priv.garshol.duke.Comparator; 21 | import no.priv.garshol.duke.Record; 22 | import no.priv.garshol.duke.RecordImpl; 23 | import no.priv.garshol.duke.comparators.Levenshtein; 24 | import no.priv.garshol.duke.comparators.WeightedLevenshtein; 25 | import no.priv.garshol.duke.comparators.WeightedLevenshtein.DefaultWeightEstimator; 26 | import org.elasticsearch.action.get.GetResponse; 27 | import org.elasticsearch.client.Client; 28 | import org.elasticsearch.common.Nullable; 29 | import org.elasticsearch.common.component.AbstractComponent; 30 | import org.elasticsearch.common.inject.Inject; 31 | import org.elasticsearch.common.settings.Settings; 32 | import org.elasticsearch.common.unit.ByteSizeValue; 33 | import org.elasticsearch.common.unit.TimeValue; 34 | import org.elasticsearch.index.fielddata.ScriptDocValues; 35 | import org.elasticsearch.node.Node; 36 | import org.elasticsearch.script.AbstractDoubleSearchScript; 37 | import org.elasticsearch.script.ExecutableScript; 38 | import org.elasticsearch.script.NativeScriptFactory; 39 | import org.elasticsearch.search.lookup.LeafDocLookup; 40 | 41 | import java.util.*; 42 | import java.util.concurrent.TimeUnit; 43 | 44 | import static no.priv.garshol.duke.utils.ObjectUtils.instantiate; 45 | import static no.priv.garshol.duke.utils.ObjectUtils.setBeanProperty; 46 | import static no.priv.garshol.duke.utils.Utils.computeBayes; 47 | 48 | /** 49 | * 50 | */ 51 | @SuppressWarnings("unchecked") 52 | /** 53 | * Entity Resolution Script for Elasticsearch 54 | * @author Yann Barraud 55 | * 56 | */ 57 | public final class EntityResolutionScript extends AbstractDoubleSearchScript { 58 | final static public String SCRIPT_NAME = "entity-resolution"; 59 | private static final String FIELDS = "fields"; 60 | private static final String COMPARATOR = "comparator"; 61 | private static final String CLEANERS = "cleaners"; 62 | private static final String PARAMS = "params"; 63 | private static final String OBJECTS = "objects"; 64 | private static final String NAME = "name"; 65 | private static final String HIGH = "high"; 66 | private static final String LOW = "low"; 67 | private static final String WEIGHTED_LEVENSHTEIN = "no.priv.garshol.duke.comparators.WeightedLevenshtein"; 68 | /** 69 | * . Average score 70 | */ 71 | private static final double AVERAGE_SCORE = 0.5; 72 | 73 | /** 74 | * . Cache to store configuration 75 | */ 76 | private final Cache>> cache; 77 | 78 | /** 79 | * . Elasticsearch client 80 | */ 81 | private final Client client; 82 | 83 | /** 84 | * . The record to be compared to 85 | */ 86 | private Record comparedRecord; 87 | 88 | /** 89 | * . Script parameters 90 | */ 91 | private Map> entityParams; 92 | 93 | /** 94 | * . Script class 95 | * 96 | * @param params params from JSON payload 97 | * @param aCache a cache to store config 98 | * @param aClient Elasticsearch client to read config from cluster 99 | */ 100 | private EntityResolutionScript( 101 | final Map params, 102 | final Cache>> aCache, 103 | final Client aClient) { 104 | 105 | if (params.get(FIELDS) == null) { 106 | throw new IllegalArgumentException( 107 | "Missing the 'fields' parameters"); 108 | } 109 | 110 | this.cache = aCache; 111 | this.client = aClient; 112 | 113 | comparedRecord = null; 114 | if (params.get("configuration") == null) { 115 | comparedRecord = 116 | configureWithFieldsOnly((ArrayList>) params 117 | .get(FIELDS)); 118 | } else { 119 | comparedRecord = 120 | configureWithFieldsAndConfiguration( 121 | (Map) params.get("configuration"), 122 | (ArrayList>) params 123 | .get("fields")); 124 | } 125 | 126 | } 127 | 128 | /** 129 | * . Reads & instantiates cleaners 130 | * 131 | * @param cleanersList array of cleaners from JSON 132 | * @return the list of instantiated cleaners 133 | */ 134 | private static List getCleaners( 135 | final List> cleanersList) { 136 | List cleanList = new ArrayList<>(); 137 | 138 | for (Map aCleaner : cleanersList) { 139 | Cleaner cleaner = (Cleaner) instantiate((String) aCleaner.get(NAME)); 140 | setParams(cleaner, aCleaner.get(PARAMS)); 141 | cleanList.add(cleaner); 142 | } 143 | return cleanList; 144 | } 145 | 146 | /** 147 | * Sets params for cleaners or comparators 148 | * 149 | * @param anObject the object to parametrize 150 | * @param params params list 151 | */ 152 | private static void setParams(Object anObject, Object params) { 153 | if (params != null) { 154 | Map paramsMap = (Map) params; 155 | for (Map.Entry entry : paramsMap.entrySet()) { 156 | setBeanProperty(anObject, entry.getKey(), entry.getValue(), null); 157 | } 158 | } 159 | } 160 | 161 | 162 | /** 163 | * Sets objects for comparators 164 | * 165 | * @param anObject the object to parametrize 166 | * @param objects objects list 167 | */ 168 | private static void setObjects(Object anObject, Object objects) { 169 | if (objects != null) { 170 | Object currentobj; 171 | HashMap list = new HashMap<>(); 172 | Map paramsMap = (Map) objects; 173 | for (Map.Entry entry : paramsMap.entrySet()) { 174 | HashMap object = entry.getValue(); 175 | String klass = object.get("class"); 176 | String name = object.get("name"); 177 | currentobj = instantiate(klass); 178 | list.put(klass, currentobj); 179 | setBeanProperty(anObject, name, klass, list); 180 | } 181 | } 182 | } 183 | 184 | /** 185 | * Gets comparator 186 | * 187 | * @param value from JSON payload 188 | * @return instantiated Comparator 189 | */ 190 | private static Comparator getComparator(final Map value) { 191 | Map compEntity = (Map) value.get(COMPARATOR); 192 | String comparatorName = 193 | ((compEntity.get(NAME) == null) ? Levenshtein.class.getName() : (String) compEntity.get(NAME)); 194 | 195 | 196 | //Comparator comp = (Comparator) instantiate(comparatorName); 197 | Comparator comp; 198 | 199 | if(compEntity.get(NAME).equals(WEIGHTED_LEVENSHTEIN)) { 200 | WeightedLevenshtein wl = new WeightedLevenshtein(); 201 | DefaultWeightEstimator we = new DefaultWeightEstimator(); 202 | setParams(we, compEntity.get(PARAMS)); 203 | wl.setEstimator(we); 204 | comp = (Comparator) wl; 205 | return comp; 206 | } 207 | 208 | comp = (Comparator) instantiate(comparatorName); 209 | setParams(comp, compEntity.get(PARAMS)); 210 | 211 | setObjects(comp, compEntity.get(OBJECTS)); 212 | 213 | return comp; 214 | } 215 | 216 | /** 217 | * . Reads field value & returns it as String 218 | * 219 | * @param field the object to cast 220 | * @return String object String value 221 | */ 222 | private static String getFieldValue(final Object field) { 223 | String result = ""; 224 | 225 | if (field instanceof ScriptDocValues.Strings) { 226 | if (!((ScriptDocValues.Strings) field).isEmpty()) { 227 | result = ((ScriptDocValues.Strings) field).getValue(); 228 | } 229 | } 230 | 231 | if (field instanceof ScriptDocValues.Doubles) { 232 | if (!((ScriptDocValues.Doubles) field).isEmpty()) { 233 | result = Double.toString(((ScriptDocValues.Doubles) field).getValue()); 234 | } 235 | } 236 | if (field instanceof ScriptDocValues.Longs) { 237 | if (!((ScriptDocValues.Longs) field).isEmpty()) { 238 | result = Long.toString(((ScriptDocValues.Longs) field).getValue()); 239 | } 240 | } 241 | if (field instanceof ScriptDocValues.GeoPoints) { 242 | if (!((ScriptDocValues.GeoPoints) field).isEmpty()) { 243 | ScriptDocValues.GeoPoints point = (ScriptDocValues.GeoPoints) field; 244 | result = String.format(Locale.getDefault(), "%s,%s", point.getLat(), point.getLon()); 245 | } 246 | } 247 | 248 | return result; 249 | } 250 | 251 | /** 252 | * Compares two records and returns the probability that they represent the 253 | * same real-world entity. 254 | * 255 | * @param r1 1st Record 256 | * @param r2 2nd Record 257 | * @param params Parameters for comparison 258 | * @return Bayesian probability 259 | */ 260 | 261 | private static double compare( 262 | final Record r1, 263 | final Record r2, 264 | final Map> params) { 265 | double prob = AVERAGE_SCORE; 266 | 267 | for (String propname : r1.getProperties()) { 268 | Collection vs1 = r1.getValues(propname); 269 | Collection vs2 = r2.getValues(propname); 270 | 271 | Boolean v1empty = true; 272 | for (String v1 : vs1) { 273 | if (!v1.equals("")) { 274 | v1empty = false; 275 | break; 276 | } 277 | } 278 | 279 | Boolean v2empty = true; 280 | for (String v2 : vs2) { 281 | if (!v2.equals("")) { 282 | v2empty = false; 283 | break; 284 | } 285 | } 286 | 287 | 288 | if (vs1.isEmpty() || vs2.isEmpty() || v1empty || v2empty) { 289 | continue; // no values to compare, so skip 290 | } 291 | 292 | Comparator comp = 293 | (Comparator) params.get(propname).get(COMPARATOR); 294 | ArrayList cleanersList = 295 | (ArrayList) params.get(propname).get(CLEANERS); 296 | 297 | Double max = (Double) params.get(propname).get(HIGH); 298 | Double min = (Double) params.get(propname).get(LOW); 299 | 300 | double high = computeProb(vs1, vs2, comp, cleanersList, max, min); 301 | prob = computeBayes(prob, high); 302 | } 303 | return prob; 304 | } 305 | 306 | private static double computeProb(Collection vs1, Collection vs2, Comparator comp, List cleanersList, Double max, Double min) { 307 | double high = 0.0; 308 | for (String v1 : vs1) { 309 | if (v1.equals("")) { 310 | continue; 311 | } 312 | 313 | v2fieldloop: 314 | for (String v2 : vs2) { 315 | if (v2.equals("")) { 316 | continue; 317 | } 318 | 319 | for (Cleaner cl : cleanersList) { 320 | v2 = cl.clean(v2); 321 | if ((v2 == null) || v2.equals("")) { 322 | continue v2fieldloop; 323 | } 324 | } 325 | double p = compare(v1, v2, max, min, comp); 326 | high = Math.max(high, p); 327 | } 328 | } 329 | return high; 330 | } 331 | 332 | /** 333 | * Returns the probability that the records v1 and v2 came from represent 334 | * the same entity, based on high and low probability settings etc. 335 | * 336 | * @param v1 1st String 337 | * @param v2 2nd String 338 | * @param high max probability 339 | * @param low min probability 340 | * @param comparator the comparator to use 341 | * @return the computed probability 342 | */ 343 | private static double compare( 344 | final String v1, 345 | final String v2, 346 | final double high, 347 | final double low, 348 | final Comparator comparator) { 349 | 350 | if (comparator == null) { 351 | return AVERAGE_SCORE; // we ignore properties with no comparator 352 | } 353 | 354 | double sim = comparator.compare(v1, v2); 355 | if (sim < AVERAGE_SCORE) { 356 | return low; 357 | } else { 358 | return ((high - AVERAGE_SCORE) * (sim * sim)) + AVERAGE_SCORE; 359 | } 360 | } 361 | 362 | /** 363 | * . Configures with data within ES index 364 | * 365 | * @param configuration configuration from JSON request 366 | * @param fields fields from JSON request 367 | * @return the record to compare others with 368 | */ 369 | private Record configureWithFieldsAndConfiguration( 370 | final Map configuration, 371 | final List> fields) { 372 | 373 | /* 374 | . Index name where to get configuration 375 | */ 376 | String configIndex = (String) configuration.get("index"); 377 | /* 378 | . Type name where to get configuration 379 | */ 380 | String configType = (String) configuration.get("type"); 381 | /* 382 | . Type ID where to get configuration 383 | */ 384 | String configName = (String) configuration.get("name"); 385 | 386 | entityParams = 387 | cache.getIfPresent(configIndex + "." + configType + "." 388 | + configName); 389 | 390 | if (entityParams == null) { 391 | GetResponse response = 392 | client.prepareGet(configIndex, configType, configName) 393 | .setPreference("_local").execute().actionGet(); 394 | 395 | if (response.isExists()) { 396 | Map entityConf = 397 | (Map) response.getSource() 398 | .get("entity"); 399 | entityParams = new HashMap<>(); 400 | if (entityConf == null) { 401 | throw new IllegalArgumentException( 402 | "No conf found in " + configIndex + "/" 403 | + configType + "/" + configName); 404 | } 405 | 406 | ArrayList> confFields = 407 | (ArrayList>) entityConf 408 | .get("fields"); 409 | 410 | if (confFields == null) { 411 | throw new IllegalArgumentException( 412 | "Bad conf found in " + configIndex + "/" 413 | + configType + "/" + configName); 414 | } 415 | 416 | for (Map confField : confFields) { 417 | HashMap map = new HashMap<>(); 418 | 419 | String field = (String) confField.get("field"); 420 | List cleanList = 421 | getCleaners((ArrayList>) confField 422 | .get(CLEANERS)); 423 | 424 | map.put(CLEANERS, cleanList); 425 | 426 | Double maxValue = 0.0; 427 | if (confField.get(HIGH) != null) { 428 | maxValue = ((Double) confField.get(HIGH)); 429 | } 430 | 431 | Double minValue = 0.0; 432 | if (confField.get(LOW) != null) { 433 | minValue = (Double) confField.get(LOW); 434 | } 435 | 436 | Comparator comp = getComparator(confField); 437 | map.put(HIGH, maxValue); 438 | map.put(LOW, minValue); 439 | map.put(COMPARATOR, comp); 440 | 441 | entityParams.put(field, map); 442 | } 443 | cache.put(configIndex + "." + configType + "." + configName, 444 | (HashMap) entityParams); 445 | } 446 | } 447 | 448 | HashMap> props = 449 | new HashMap<>(); 450 | 451 | readFields(fields, props); 452 | return new RecordImpl(props); 453 | } 454 | 455 | private void readFields(List> fields, Map> props) { 456 | for (Map value : fields) { 457 | String field = (String) value.get("field"); 458 | String fieldValue = (String) value.get("value"); 459 | for (Cleaner cl : (ArrayList) entityParams.get(field).get(CLEANERS)) { 460 | fieldValue = cl.clean(fieldValue); 461 | } 462 | props.put(field, Collections.singleton(fieldValue)); 463 | } 464 | } 465 | 466 | /** 467 | * . Configures with data from JSON payload only 468 | * 469 | * @param fieldsParams fields parameters from JSON 470 | * @return the record for comparison 471 | */ 472 | private Record configureWithFieldsOnly( 473 | final List> fieldsParams) { 474 | 475 | Map> props = 476 | new HashMap<>(); 477 | entityParams = new HashMap<>(); 478 | 479 | for (Map value : fieldsParams) { 480 | HashMap map = new HashMap<>(); 481 | 482 | String field = (String) value.get("field"); 483 | 484 | List cleanList = 485 | getCleaners((ArrayList>) value.get(CLEANERS)); 486 | 487 | map.put(CLEANERS, cleanList); 488 | 489 | Double maxValue = 0.0; 490 | if (value.get(HIGH) != null) { 491 | maxValue = (Double) value.get(HIGH); 492 | } 493 | 494 | Double minValue = 0.0; 495 | if (value.get(LOW) != null) { 496 | minValue = (Double) value.get(LOW); 497 | } 498 | 499 | Comparator comp = getComparator(value); 500 | 501 | map.put(HIGH, maxValue); 502 | map.put(LOW, minValue); 503 | map.put(COMPARATOR, comp); 504 | 505 | entityParams.put(field, map); 506 | } 507 | 508 | readFields(fieldsParams, props); 509 | return new RecordImpl(props); 510 | } 511 | 512 | /** 513 | * . Computes probability that objects are the same 514 | * 515 | * @return float the computed score 516 | */ 517 | @Override 518 | public double runAsDouble() { 519 | HashMap> props = 520 | new HashMap<>(); 521 | LeafDocLookup doc = doc(); 522 | Collection docKeys = comparedRecord.getProperties(); 523 | 524 | for (String key : docKeys) { 525 | if (doc.containsKey(key)) { 526 | String value = (doc.get(key) == null ? "" : getFieldValue(doc.get(key))); 527 | props.put(key, value == null 528 | ? Collections.singleton("") 529 | : Collections.singleton(value)); 530 | } 531 | } 532 | Record r2 = new RecordImpl(props); 533 | return compare(comparedRecord, r2, entityParams); 534 | } 535 | 536 | /** 537 | 538 | */ 539 | 540 | /** 541 | * Factory 542 | */ 543 | public static class Factory extends AbstractComponent implements 544 | NativeScriptFactory { 545 | /** 546 | * . Node where the plugin is instantiated 547 | */ 548 | private final Node node; 549 | /** 550 | * . Cache to store configuration 551 | */ 552 | private final Cache>> cache; 553 | 554 | /** 555 | * . This constructor will be called by guice during initialization 556 | * 557 | * @param aNode node reference injecting the reference to current node to 558 | * get access to node's client 559 | * @param settings cluster settings 560 | */ 561 | @SuppressWarnings("unchecked") 562 | @Inject 563 | public Factory(final Node aNode, final Settings settings) { 564 | super(settings); 565 | // Node is not fully initialized here 566 | // All we can do is save a reference to it for future use 567 | this.node = aNode; 568 | 569 | TimeValue expire = 570 | settings.getAsTime("entity-resolution.cache.expire", 571 | new TimeValue(1L, TimeUnit.HOURS)); 572 | ByteSizeValue size = 573 | settings.getAsBytesSize( 574 | "entity-resolution.cache.size", null); 575 | CacheBuilder cacheBuilder = 576 | CacheBuilder.newBuilder(); 577 | cacheBuilder.expireAfterAccess(expire.seconds(), TimeUnit.SECONDS); 578 | if (size != null) { 579 | cacheBuilder.maximumSize(size.bytes()); 580 | } 581 | cache = cacheBuilder.build(); 582 | } 583 | 584 | /** 585 | * This method is called for every search on every shard. 586 | * 587 | * @param params list of script parameters passed with the query 588 | * @return new native script 589 | */ 590 | @Override 591 | public final ExecutableScript newScript( 592 | @Nullable final Map params) { 593 | if (params.get("entity") == null) { 594 | throw new IllegalArgumentException( 595 | "Missing the parameters"); 596 | } 597 | 598 | return new EntityResolutionScript( 599 | (Map) params.get("entity"), 600 | cache, 601 | node.client()); 602 | } 603 | 604 | /** 605 | * Indicates if document scores may be needed by the produced scripts. 606 | * 607 | * @return {@code true} if scores are needed. 608 | */ 609 | @Override 610 | public boolean needsScores() { 611 | return false; 612 | } 613 | 614 | } 615 | } 616 | --------------------------------------------------------------------------------