SearchDocTransform.kt 8.01 KB
Newer Older
Jonas Waeber's avatar
Jonas Waeber committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * search-doc-service
 * Copyright (C) 2020 Memoriav
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package org.memobase

import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.json
import org.apache.logging.log4j.LogManager

class SearchDocTransform(mapping: String) {

    private val log = LogManager.getLogger("SearchDocTransform")

    private val transformConfig = YamlLoader(mapping).load()

    fun transform(input: Map<String, JsonObject>): JsonObject {
        return json {
            obj(input["record"].let { record ->
                record?.mapNotNull { entry ->
                    when (val transform = transformConfig.getTransform(entry.key)) {
                        is LiteralTransform ->
                            listOf(extractPair(entry.value, transform.target))
                        is EntityTransform ->
                            when (val value = entry.value) {
                                is String -> {
                                    input[value]?.let { entity ->
                                        entityTransformSelection(input, entity, transform)
                                    }
                                }
                                is JsonObject -> {
                                    input[value["@id"] as String]?.let { entity ->
                                        entityTransformSelection(input, entity, transform)
                                    }
                                }
                                is JsonArray<*> -> {
                                    value.flatMap { children ->
                                        children as JsonObject
                                        input[children["@id"] as String]?.let { entity ->
                                            entityTransformSelection(input, entity, transform)
                                        }.orEmpty()
                                    }
                                }
                                else -> emptyList()
                            }
                        null -> emptyList()
                    }
                }?.flatten().orEmpty().filterNotNull().asIterable()
            })
        }
    }

    private fun entityTransformSelection(
        input: Map<String, JsonObject>,
        entity: JsonObject,
        transform: EntityTransform
    ): List<Pair<String, Any>> {
        return when {
            transform.isDate -> {
                extractDateEntity(entity, transform)
            }
            transform.conditionalTargets.isNotEmpty() -> {
                transform.conditionalTargets.map {
                    if (entity.containsKey(it.conditionProperty) && entity[it.conditionProperty] == it.conditionPattern) {
80
81
82
83
84
85
86
87
88
89
90
91
                        if (transform.source.contains('|')) {
                            val sourceFields = transform.source.split('|')
                            sourceFields.mapNotNull { sourceField ->
                                extractPair(entity[sourceField], it.target)
                            }
                        } else {
                            val subPair = extractPair(entity[transform.source], it.target)
                            if (subPair == null)
                                emptyList()
                            else
                                listOf(subPair)
                        }
Jonas Waeber's avatar
Jonas Waeber committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
                    } else {
                        emptyList()
                    }
                }.flatten()
            }
            transform.isCreationRelation -> {
                extractCreationRelationAndAgents(input, entity)
            }
            else -> {
                val pair = extractPair(entity[transform.source], transform.target)
                if (pair == null) emptyList()
                else listOf(pair)
            }
        }
    }

    private fun extractPair(value: Any?, targetField: String): Pair<String, Any>? {
        return when (value) {
            is String ->
                Pair(targetField, value)
            is JsonObject ->
                Pair(targetField, mapOf(Pair(value["@language"], value["@value"])))
114
115
            is JsonArray<*> -> {
                val results = value.mapNotNull {
Jonas Waeber's avatar
Jonas Waeber committed
116
117
118
119
120
                    when (it) {
                        is String -> it
                        is JsonObject -> Pair(it["@language"], it["@value"])
                        else -> null
                    }
121
122
123
124
125
126
127
128
129
130
131
132
133
                }
                when {
                    results.isEmpty() -> {
                        null
                    }
                    results[0] is String -> {
                        Pair(targetField, results)
                    }
                    else -> {
                        Pair(targetField, (results as List<Pair<Any, Any>>).toMap())
                    }
                }
            }
Jonas Waeber's avatar
Jonas Waeber committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
            else -> {
                log.error("Could not parse literal value: $value.")
                null
            }
        }
    }

    private fun extractDateEntity(entity: JsonObject, transform: Transform): List<Pair<String, Any>> {
        val isNormalized = entity.containsKey("rico:normalizedDateValue")

        val date = if (isNormalized) {
            entity["rico:normalizedDateValue"] as String
        } else {
            entity["rico:expressedDate"] as String
        }
        val qualifier = entity["rico:dateQualifier"] as String?
        val certainty = entity["rico:certainty"] as String?
        val result = mutableListOf<Pair<String, Any>>(
            Pair(transform.target + ".date", date)
        )
        if (qualifier != null) {
            result.add(
                Pair(transform.target + ".qualifier", qualifier)
            )
        }
        if (certainty != null) {
            result.add(
                Pair(transform.target + ".certainty", certainty)
            )
        }
        val facetList = when (entity["@type"] as String) {
            "rico:SingleDate" ->
                if (isNormalized)
                    DateFacetBuilder.buildFromNormalizedSingleDate(date)
                else emptyList()
            "rico:DateRange" ->
                if (isNormalized)
                    DateFacetBuilder.buildFromNormalizedDateRange(date)
                else emptyList()
            else -> emptyList()
        }
        if (facetList.isNotEmpty())
            result.add(Pair(transform.target + ".facet", facetList))
        return result
    }

    private fun extractCreationRelationAndAgents(
        input: Map<String, JsonObject>,
        creationRelation: JsonObject
    ): List<Pair<String, Any>> {
        val type = creationRelation["rico:type"] as String
        val name = creationRelation["rico:name"] as String
        val target = (creationRelation["rico:creationRelationHasTarget"] as JsonObject)["@id"] as String

        val agent = input[target]
        return if (agent == null) {
            emptyList()
        } else {
            val agentType = agent["@type"] as String
            val agentName = agent["rico:name"] as Any
            val pair1 =
                extractPair(name, "${agentType.split(':')[1]}${type}Raw.relation")
            val pair2 =
                extractPair(agentName, "${agentType.split(':')[1]}${type}Raw.name")

            val result = mutableListOf<Pair<String, Any>>()
            if (pair1 != null) {
                result.add(pair1)
            }
            if (pair2 != null) {
                result.add(pair2)
            }
            result
        }
    }
}