1
|
package eu.dnetlib.data.dedup;
|
2
|
|
3
|
import java.io.IOException;
|
4
|
import java.util.*;
|
5
|
import java.util.stream.Collectors;
|
6
|
import javax.annotation.Resource;
|
7
|
|
8
|
import com.google.common.base.Function;
|
9
|
import com.google.common.base.Joiner;
|
10
|
import com.google.common.base.Splitter;
|
11
|
import com.google.common.collect.Iterables;
|
12
|
import com.google.common.collect.Lists;
|
13
|
import com.google.common.collect.Maps;
|
14
|
import com.google.common.collect.Sets;
|
15
|
import com.google.protobuf.GeneratedMessage;
|
16
|
import eu.dnetlib.data.mapreduce.util.OafDecoder;
|
17
|
import eu.dnetlib.data.mapreduce.util.OafEntityDecoder;
|
18
|
import eu.dnetlib.data.proto.OafProtos.Oaf;
|
19
|
import eu.dnetlib.data.transform.AbstractProtoMapper;
|
20
|
import eu.dnetlib.data.transform.OafEntityMerger;
|
21
|
import eu.dnetlib.data.transform.SolrProtoMapper;
|
22
|
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
|
23
|
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
|
24
|
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
|
25
|
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
|
26
|
import eu.dnetlib.functionality.index.client.IndexClient;
|
27
|
import eu.dnetlib.functionality.index.client.IndexClientException;
|
28
|
import eu.dnetlib.functionality.index.client.response.LookupResponse;
|
29
|
import eu.dnetlib.functionality.index.client.solr.SolrIndexClient;
|
30
|
import eu.dnetlib.functionality.index.client.solr.SolrIndexClientFactory;
|
31
|
import eu.dnetlib.functionality.modular.ui.dedup.SimilarityGroup;
|
32
|
import eu.dnetlib.pace.config.DedupConfig;
|
33
|
import eu.dnetlib.pace.model.Field;
|
34
|
import eu.dnetlib.pace.model.FieldDef;
|
35
|
import eu.dnetlib.pace.model.FieldValueImpl;
|
36
|
import eu.dnetlib.pace.model.ProtoDocumentBuilder;
|
37
|
import org.apache.commons.codec.binary.Base64;
|
38
|
import org.apache.commons.lang.StringUtils;
|
39
|
import org.apache.commons.logging.Log;
|
40
|
import org.apache.commons.logging.LogFactory;
|
41
|
|
42
|
import org.apache.solr.client.solrj.impl.CloudSolrClient;
|
43
|
import org.apache.solr.common.SolrInputDocument;
|
44
|
import org.dom4j.DocumentException;
|
45
|
import org.springframework.beans.factory.annotation.Autowired;
|
46
|
import org.springframework.beans.factory.annotation.Value;
|
47
|
|
48
|
public class DedupIndexDAO {
|
49
|
|
50
|
private static final Log log = LogFactory.getLog(DedupIndexDAO.class);
|
51
|
|
52
|
private static final String ID_PREFIX_REGEX = "^\\d\\d\\|";
|
53
|
|
54
|
private static final Map<String, Map<String, String>> paths = Maps.newHashMap();
|
55
|
|
56
|
static {
|
57
|
paths.put("result", new HashMap<>());
|
58
|
paths.put("organization", new HashMap<>());
|
59
|
paths.put("person", new HashMap<>());
|
60
|
|
61
|
paths.get("result").put("provenance", "collectedfrom/value");
|
62
|
paths.get("organization").put("provenance", "collectedfrom/value");
|
63
|
paths.get("person").put("provenance", "collectedfrom/value");
|
64
|
|
65
|
paths.get("result").put("title", "result/metadata/title/value");
|
66
|
paths.get("result").put("dateofacceptance", "result/metadata/dateofacceptance/value");
|
67
|
paths.get("result").put("description", "result/metadata/description/value");
|
68
|
paths.get("result").put("author", "result/metadata/author/fullname");
|
69
|
|
70
|
paths.get("organization").put("legalname", "organization/metadata/legalname/value");
|
71
|
paths.get("organization").put("legalshortname", "organization/metadata/legalshortname/value");
|
72
|
paths.get("organization").put("websiteurl", "organization/metadata/websiteurl/value");
|
73
|
paths.get("organization").put("country", "organization/metadata/country/classid");
|
74
|
|
75
|
paths.get("person").put("fullname", "person/metadata/fullname/value");
|
76
|
}
|
77
|
|
78
|
@Resource
|
79
|
private UniqueServiceLocator serviceLocator;
|
80
|
|
81
|
/**
|
82
|
* The index client factory.
|
83
|
*/
|
84
|
@Autowired
|
85
|
private SolrIndexClientFactory indexClientFactory;
|
86
|
|
87
|
private IndexClient indexClient = null;
|
88
|
|
89
|
@Value("${dnet.dedup.index.collection}")
|
90
|
private String dedupIndexCollection;
|
91
|
|
92
|
public OafResult search(final String type, final String userQuery, final String actionSet, final int start, final int rows, final String fields)
|
93
|
throws Exception {
|
94
|
|
95
|
final String cqlQuery =
|
96
|
String.format("(>s=SOLR s.q.op=AND) and oaftype = %s and actionset exact \"%s\" and deletedbyinference = false and %s", type, actionSet,
|
97
|
userQuery);
|
98
|
|
99
|
final LookupResponse rsp = getIndexClient().lookup(cqlQuery, null, start, (start + rows) - 1);
|
100
|
|
101
|
final List<String> fieldList = Lists.newLinkedList(Splitter.on(",").omitEmptyStrings().trimResults().split(fields));
|
102
|
final List<Map<String, String>> resList = Lists.newLinkedList(Iterables.transform(toOaf(rsp), getOaf2FieldMapFunction(type, fieldList)));
|
103
|
|
104
|
return new OafResult(rsp.getTotal(), resList);
|
105
|
|
106
|
}
|
107
|
|
108
|
public OafResult searchById(final String actionSet, final String type, final String objidentifier, final List<String> fields) throws Exception {
|
109
|
final String cqlQuery = "objidentifier exact \"" + objidentifier + "\" and actionset exact \"" + actionSet + "\"";
|
110
|
|
111
|
final LookupResponse rsp = getIndexClient().lookup(cqlQuery, null, 0, 1);
|
112
|
|
113
|
final Iterable<Oaf> oafList = toOaf(rsp);
|
114
|
|
115
|
final List<Map<String, String>> resList = Lists.newLinkedList(Iterables.transform(oafList, getOaf2FieldMapFunction(type, fields)));
|
116
|
|
117
|
return new OafResult(rsp.getTotal(), resList);
|
118
|
}
|
119
|
|
120
|
public boolean commit(final SimilarityGroup group) throws Exception {
|
121
|
|
122
|
int commitStatus = 0;
|
123
|
int addStatus = 0;
|
124
|
|
125
|
log.info("starting index update");
|
126
|
|
127
|
final SolrIndexClient indexClient = (SolrIndexClient) getIndexClient();
|
128
|
final SolrProtoMapper mapper = initProtoMapper();
|
129
|
|
130
|
final Function<Oaf, SolrInputDocument> oaf2solr = oaf2solr(group, mapper);
|
131
|
final List<SolrInputDocument> buffer = Lists.newLinkedList();
|
132
|
|
133
|
// mark as deleted all the documents in the group
|
134
|
final List<Oaf> groupDocs = markDeleted(asOafBuilder(parseBase64(queryIndex(group.getGroup(), group.getActionSet()))));
|
135
|
buffer.addAll(asIndexDocs(oaf2solr, groupDocs));
|
136
|
|
137
|
// elect a new representative
|
138
|
final SolrInputDocument newRoot = oaf2solr.apply(OafEntityMerger.merge(getDedupConf(group), newRootId(group), groupDocs).build());
|
139
|
final String newRootId = (String) newRoot.getFieldValue("objidentifier");
|
140
|
// newRoot.setField("actionset", dedupConf.getWf().getConfigurationId());
|
141
|
buffer.add(newRoot);
|
142
|
|
143
|
// mark as non deleted the documents taken away from the group
|
144
|
final List<Oaf> dissimDocs = markUnDeleted(asOafBuilder(parseBase64(queryIndex(unique(group.getDissimilar()), group.getActionSet()))));
|
145
|
buffer.addAll(asIndexDocs(oaf2solr, dissimDocs));
|
146
|
|
147
|
log.debug(String.format("adding %d documents to index %s", buffer.size(), dedupIndexCollection));
|
148
|
|
149
|
// add the changes to the server
|
150
|
addStatus = indexClient.feed(buffer);
|
151
|
log.debug("solr add status: " + addStatus);
|
152
|
|
153
|
// delete the old representatives, avoiding to remove the current one (if it didn't change)
|
154
|
log.debug(String.format("deleting %d documents from index %s", group.getRootIds().size(), dedupIndexCollection));
|
155
|
for (final String rootId : Iterables.filter(group.getRootIds(), rootId -> !rootId.equals(newRootId))) {
|
156
|
indexClient.remove(mapper.getRecordId(rootId, group.getActionSet()));
|
157
|
}
|
158
|
|
159
|
commitStatus = indexClient.commit().getStatus();
|
160
|
|
161
|
log.debug("solr commit status: " + commitStatus);
|
162
|
|
163
|
return (addStatus == 0) && (commitStatus == 0);
|
164
|
}
|
165
|
|
166
|
private Iterable<Oaf> toOaf(final LookupResponse rsp) {
|
167
|
return Iterables.transform(rsp.getRecords(), getXml2OafFunction());
|
168
|
}
|
169
|
|
170
|
private Iterable<Oaf> parseBase64(final Iterable<String> r) {
|
171
|
return Iterables.transform(r, getXml2OafFunction());
|
172
|
}
|
173
|
|
174
|
protected Function<String, Oaf> getXml2OafFunction() {
|
175
|
return s -> {
|
176
|
// final String base64 = s.replaceAll("<record.*>", "").replace("</record>", "");
|
177
|
final String base64 = StringUtils.substringBefore(StringUtils.substringAfter(s, ">"), "<");
|
178
|
try {
|
179
|
final byte[] oafBytes = Base64.decodeBase64(base64);
|
180
|
final Oaf oaf = OafDecoder.decode(oafBytes).getOaf();
|
181
|
return oaf;
|
182
|
} catch (final Throwable e) {
|
183
|
throw new IllegalArgumentException("unable to decode base64 encoded Oaf object: " + base64);
|
184
|
}
|
185
|
};
|
186
|
}
|
187
|
|
188
|
private SolrProtoMapper initProtoMapper() throws DocumentException, ISLookUpException, ISLookUpDocumentNotFoundException {
|
189
|
return new SolrProtoMapper(
|
190
|
serviceLocator
|
191
|
.getService(ISLookUpService.class)
|
192
|
.getResourceProfileByQuery(
|
193
|
"collection('')//RESOURCE_PROFILE["
|
194
|
+ ".//RESOURCE_TYPE/@value = 'MDFormatDSResourceType' and "
|
195
|
+ ".//NAME='OPENAIRE']//LAYOUT[@name='index']/FIELDS"));
|
196
|
}
|
197
|
|
198
|
private String getResourceProfileByQuery(final String xquery) throws ISLookUpException {
|
199
|
log.debug("quering for service property: " + xquery);
|
200
|
final String res = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(xquery);
|
201
|
if (StringUtils.isBlank(res)) throw new IllegalStateException("unable to find unique service property, xquery: " + xquery);
|
202
|
return res;
|
203
|
}
|
204
|
|
205
|
protected Function<Oaf, Map<String, String>> getOaf2FieldMapFunction(final String type, final List<String> fields) {
|
206
|
return oaf -> {
|
207
|
|
208
|
final Map<String, String> res = Maps.newHashMap();
|
209
|
final String oafId = cleanId(oaf.getEntity().getId());
|
210
|
|
211
|
final List<String> idList = oaf.getEntity().getChildrenList().stream()
|
212
|
.map(e -> e.getId())
|
213
|
.map(s -> cleanId(s))
|
214
|
.collect(Collectors.toList());
|
215
|
if (idList.isEmpty()) {
|
216
|
idList.add(oafId);
|
217
|
}
|
218
|
res.put("id", oafId);
|
219
|
res.put("idList", Joiner.on(",").join(idList));
|
220
|
res.put("groupSize", idList.isEmpty() ? "1" : idList.size() + "");
|
221
|
|
222
|
for (final String fieldName : fields) {
|
223
|
|
224
|
res.put(fieldName, Joiner.on("; ").skipNulls().join(getFieldValues((GeneratedMessage) oaf.getEntity(), fieldName, paths.get(type).get(fieldName))));
|
225
|
}
|
226
|
|
227
|
return res;
|
228
|
};
|
229
|
}
|
230
|
|
231
|
private List<String> getFieldValues(final GeneratedMessage m, final String fieldName, final String path) {
|
232
|
return new SolrDocumentMapper().processPath(m, fieldName, path).stream()
|
233
|
.map(o -> o.toString())
|
234
|
.collect(Collectors.toCollection(LinkedList::new));
|
235
|
}
|
236
|
|
237
|
class SolrDocumentMapper extends AbstractProtoMapper {
|
238
|
|
239
|
public List<Object> processPath(final GeneratedMessage m, final String fieldName, final String path) {
|
240
|
final FieldDef fd = new FieldDef();
|
241
|
fd.setName(fieldName);
|
242
|
return processPath(m, fd, path);
|
243
|
}
|
244
|
}
|
245
|
|
246
|
private String cleanId(final String id) {
|
247
|
return id.replaceFirst(ID_PREFIX_REGEX, "");
|
248
|
}
|
249
|
|
250
|
private IndexClient getIndexClient() throws IndexClientException, ISLookUpDocumentNotFoundException, ISLookUpException {
|
251
|
if (indexClient == null) {
|
252
|
indexClient = indexClientFactory.getClient(dedupIndexCollection);
|
253
|
}
|
254
|
return indexClient;
|
255
|
}
|
256
|
|
257
|
private Iterable<String> queryIndex(final Iterable<String> ids, final String actionset) {
|
258
|
return Iterables.transform(ids, id -> {
|
259
|
try {
|
260
|
final String cql = "objidentifier exact \"" + id + "\" and actionset exact \"" + actionset + "\"";
|
261
|
final LookupResponse rsp = getIndexClient().lookup(cql, null, 0, 1);
|
262
|
|
263
|
log.debug(String.format("query index for id '%s', found '%d'", id, rsp.getTotal()));
|
264
|
|
265
|
return Iterables.getOnlyElement(rsp.getRecords());
|
266
|
} catch (final Throwable e) {
|
267
|
log.error(e);
|
268
|
throw new RuntimeException("unable to query id: " + id, e);
|
269
|
}
|
270
|
});
|
271
|
}
|
272
|
|
273
|
private List<Oaf> markDeleted(final Iterable<Oaf.Builder> builders) {
|
274
|
return Lists.newArrayList(Iterables.transform(builders, builder -> {
|
275
|
// TODO add more changes to the Oaf object here as needed.
|
276
|
builder.getDataInfoBuilder().setDeletedbyinference(true);
|
277
|
return builder.build();
|
278
|
}));
|
279
|
}
|
280
|
|
281
|
private List<Oaf> markUnDeleted(final Iterable<Oaf.Builder> builders) {
|
282
|
return Lists.newArrayList(Iterables.transform(builders, builder -> {
|
283
|
// TODO add more changes to the Oaf object here as needed.
|
284
|
builder.getDataInfoBuilder().setDeletedbyinference(false);
|
285
|
return builder.build();
|
286
|
}));
|
287
|
}
|
288
|
|
289
|
private Iterable<Oaf.Builder> asOafBuilder(final Iterable<Oaf> oaf) {
|
290
|
return Iterables.transform(oaf, oaf1 -> Oaf.newBuilder(oaf1));
|
291
|
}
|
292
|
|
293
|
private String newRootId(final SimilarityGroup group) {
|
294
|
return "dedup_wf_001::" + Collections.min(group.getGroup()).replaceFirst("^.*::", "");
|
295
|
// else return Collections.min(group.getRootIds());
|
296
|
}
|
297
|
|
298
|
private List<SolrInputDocument> asIndexDocs(final Function<Oaf, SolrInputDocument> mapper, final Iterable<Oaf> protos) {
|
299
|
return Lists.newArrayList(Iterables.transform(protos, mapper));
|
300
|
}
|
301
|
|
302
|
private Function<Oaf, SolrInputDocument> oaf2solr(final SimilarityGroup group, final SolrProtoMapper mapper) {
|
303
|
return oaf -> {
|
304
|
try {
|
305
|
return mapper.map(oaf, group.getDate(), "", group.getActionSet());
|
306
|
} catch (final Throwable e) {
|
307
|
throw new IllegalArgumentException("unable to map proto to index document", e);
|
308
|
}
|
309
|
};
|
310
|
}
|
311
|
|
312
|
private Set<String> unique(final Map<String, Set<String>> map) {
|
313
|
final Set<String> res = Sets.newHashSet();
|
314
|
for (final Set<String> ids : map.values()) {
|
315
|
res.addAll(ids);
|
316
|
}
|
317
|
|
318
|
return res;
|
319
|
}
|
320
|
|
321
|
private DedupConfig getDedupConf(final SimilarityGroup group) throws IOException {
|
322
|
final Map<String, String> config = Maps.newHashMap();
|
323
|
config.put("entityType", group.getEntityType().getType());
|
324
|
config.put("configurationId", group.getActionSet());
|
325
|
final DedupConfig dedupConf = DedupConfig.loadDefault(config);
|
326
|
return dedupConf;
|
327
|
}
|
328
|
|
329
|
}
|