-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy patharrayLevenshtein.cpp
More file actions
690 lines (623 loc) · 33 KB
/
Copy patharrayLevenshtein.cpp
File metadata and controls
690 lines (623 loc) · 33 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
#include <Columns/ColumnArray.h>
#include <Columns/ColumnDecimal.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnTuple.h>
#include <Common/levenshteinDistance.h>
#include <Common/PODArray.h>
#include <Common/iota.h>
#include <Common/VectorWithMemoryTracking.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/DataTypesNumber.h>
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionHelpers.h>
#include <IO/WriteHelpers.h>
#include <numeric>
#include <span>
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int LOGICAL_ERROR;
extern const int SIZES_OF_ARRAYS_DONT_MATCH;
}
/// arrayLevenshteinDistance([1,2,3,4], [1,3,2,4]) = 2
/// arrayLevenshteinDistanceWeighted([1,2,3,4], [1,3,2,4]) = 2
template <typename T>
class FunctionArrayLevenshtein final : public IFunction
{
public:
static constexpr auto name = T::name;
static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionArrayLevenshtein<T>>(); }
String getName() const override { return name; }
size_t getNumberOfArguments() const override { return T::arguments; }
bool useDefaultImplementationForConstants() const override { return true; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
{
FunctionArgumentDescriptors args_descriptors;
args_descriptors = FunctionArgumentDescriptors{
{"from", static_cast<FunctionArgumentDescriptor::TypeValidator>(&isArray), nullptr, "Array"},
{"to", static_cast<FunctionArgumentDescriptor::TypeValidator>(&isArray), nullptr, "Array"},
{"from_weights", static_cast<FunctionArgumentDescriptor::TypeValidator>(&isArray), nullptr, "Array"},
{"to_weights", static_cast<FunctionArgumentDescriptor::TypeValidator>(&isArray), nullptr, "Array"},
};
validateFunctionArguments(*this, arguments, args_descriptors);
VectorWithMemoryTracking<DataTypePtr> nested_types;
nested_types.reserve(2);
for (size_t index = 2; index < 4; ++index)
{
const DataTypeArray * array_type = checkAndGetDataType<DataTypeArray>(arguments[index].type.get());
const DataTypePtr nested_type = array_type->getNestedType();
nested_types.emplace_back(nested_type);
if (!(isFloat(nested_type) || isInteger(nested_type)))
throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Argument {} of function {} must be a numeric array. Found {} instead.",
toString(index + 1),
getName(),
nested_type->getName());
}
if (nested_types[0]->getName() != nested_types[1]->getName())
throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Arguments 3 and 4 of function {} must be arrays of the same types. Found {} and {} instead.",
getName(),
nested_types[0]->getName(),
nested_types[1]->getName());
return std::make_shared<DataTypeFloat64>();
}
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{
size_t num_arguments = arguments.size();
Columns holders(num_arguments);
VectorWithMemoryTracking<const ColumnArray *> columns(num_arguments);
for (size_t i = 0; i < num_arguments; ++i)
{
holders[i] = arguments[i].column->convertToFullColumnIfConst();
if (holders[i]->size() != input_rows_count)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Function {} has unequal number of rows in columns: "
"expected {}, got {} for column {}",
getName(),
input_rows_count,
holders[i]->size(),
holders[i]->getName());
columns[i] = assert_cast<const ColumnArray*>(holders[i].get());
}
return execute(columns);
}
private:
ColumnPtr execute(VectorWithMemoryTracking<const ColumnArray *>) const
{
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unknown function {}. "
"Supported names: 'arrayLevenshteinDistance', 'arrayLevenshteinDistanceWeighted', 'arraySimilarity'",
getName());
}
template <typename N, typename Result>
bool levenshteinString(VectorWithMemoryTracking<const ColumnArray *> columns, Result::Container & res_values) const
{
const N * from_data = checkAndGetColumn<N>(&columns[0]->getData());
const N * to_data = checkAndGetColumn<N>(&columns[1]->getData());
if (!from_data || !to_data)
return false;
if (T::arguments == 4)
{
if constexpr (std::is_same_v<Result, ColumnFloat64>)
{
if (!(
levenshteinWeightedString<N, UInt8>(columns, res_values)
|| levenshteinWeightedString<N, UInt16>(columns, res_values)
|| levenshteinWeightedString<N, UInt32>(columns, res_values)
|| levenshteinWeightedString<N, UInt64>(columns, res_values)
|| levenshteinWeightedString<N, UInt128>(columns, res_values)
|| levenshteinWeightedString<N, UInt256>(columns, res_values)
|| levenshteinWeightedString<N, Int8>(columns, res_values)
|| levenshteinWeightedString<N, Int16>(columns, res_values)
|| levenshteinWeightedString<N, Int32>(columns, res_values)
|| levenshteinWeightedString<N, Int64>(columns, res_values)
|| levenshteinWeightedString<N, Int128>(columns, res_values)
|| levenshteinWeightedString<N, Int256>(columns, res_values)
|| levenshteinWeightedString<N, Float32>(columns, res_values)
|| levenshteinWeightedString<N, Float64>(columns, res_values)))
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unexpected code branch of function {}. No fitting levenshteinWeightedString",
getName());
return true;
}
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unexpected code branch of function {}. Wrong expected result type in levenshteinString",
getName());
}
const ColumnArray::Offsets & from_offsets = columns[0]->getOffsets();
ColumnArray::Offset prev_from_offset = 0;
const ColumnArray::Offsets & to_offsets = columns[1]->getOffsets();
ColumnArray::Offset prev_to_offset = 0;
const auto extract_array = [](const N * data, size_t prev_offset, size_t count)
{
VectorWithMemoryTracking<std::string_view> temp;
temp.reserve(count);
for (size_t j = 0; j < count; ++j) { temp.emplace_back(data->getDataAt(prev_offset + j)); }
return temp;
};
using ElementType = Result::Container::value_type;
for (size_t row = 0; row < columns[0]->size(); row++)
{
const size_t m = from_offsets[row] - prev_from_offset;
const size_t n = to_offsets[row] - prev_to_offset;
const VectorWithMemoryTracking<std::string_view> from = extract_array(from_data, prev_from_offset, m);
const VectorWithMemoryTracking<std::string_view> to = extract_array(to_data, prev_to_offset, n);
prev_from_offset = from_offsets[row];
prev_to_offset = to_offsets[row];
res_values[row] = static_cast<ElementType>(levenshteinDistance<std::string_view>(from, to));
}
return true;
}
template <typename N, typename Result>
bool levenshteinNumber(VectorWithMemoryTracking<const ColumnArray *> columns, Result::Container & res_values) const
{
const ColumnVectorOrDecimal<N> * column_from = checkAndGetColumn<ColumnVectorOrDecimal<N>>(&columns[0]->getData());
const ColumnVectorOrDecimal<N> * column_to = checkAndGetColumn<ColumnVectorOrDecimal<N>>(&columns[1]->getData());
if (!column_from || !column_to)
return false;
if (T::arguments == 4)
{
if constexpr (std::is_same_v<Result, ColumnFloat64>)
{
if (!(
levenshteinWeightedNumber<N, UInt8>(columns, res_values)
|| levenshteinWeightedNumber<N, UInt16>(columns, res_values)
|| levenshteinWeightedNumber<N, UInt32>(columns, res_values)
|| levenshteinWeightedNumber<N, UInt64>(columns, res_values)
|| levenshteinWeightedNumber<N, UInt128>(columns, res_values)
|| levenshteinWeightedNumber<N, UInt256>(columns, res_values)
|| levenshteinWeightedNumber<N, Int8>(columns, res_values)
|| levenshteinWeightedNumber<N, Int16>(columns, res_values)
|| levenshteinWeightedNumber<N, Int32>(columns, res_values)
|| levenshteinWeightedNumber<N, Int64>(columns, res_values)
|| levenshteinWeightedNumber<N, Int128>(columns, res_values)
|| levenshteinWeightedNumber<N, Int256>(columns, res_values)
|| levenshteinWeightedNumber<N, Float32>(columns, res_values)
|| levenshteinWeightedNumber<N, Float64>(columns, res_values)))
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unexpected code branch of function {}. No fitting levenshteinWeightedNumber",
getName());
return true;
}
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unexpected code branch of function {}. Wrong expected result type in levenshteinNumber",
getName());
}
const ColumnArray::Offsets & from_offsets = columns[0]->getOffsets();
ColumnArray::Offset prev_from_offset = 0;
const ColumnArray::Offsets & to_offsets = columns[1]->getOffsets();
ColumnArray::Offset prev_to_offset = 0;
using ElementType = Result::Container::value_type;
for (size_t row = 0; row < columns[0]->size(); row++)
{
std::span<const N> from(column_from->getData().begin() + prev_from_offset, from_offsets[row] - prev_from_offset);
prev_from_offset = from_offsets[row];
std::span<const N> to(column_to->getData().begin() + prev_to_offset, to_offsets[row] - prev_to_offset);
prev_to_offset = to_offsets[row];
res_values[row] = static_cast<ElementType>(levenshteinDistance<N>(from, to));
}
return true;
}
template<typename Result>
void levenshteinGeneric(VectorWithMemoryTracking<const ColumnArray *> columns, Result::Container & res_values) const
{
if (T::arguments == 4)
{
if constexpr (std::is_same_v<Result, ColumnFloat64>)
{
if (!(
levenshteinWeightedGeneric<UInt8>(columns, res_values)
|| levenshteinWeightedGeneric<UInt16>(columns, res_values)
|| levenshteinWeightedGeneric<UInt32>(columns, res_values)
|| levenshteinWeightedGeneric<UInt64>(columns, res_values)
|| levenshteinWeightedGeneric<UInt128>(columns, res_values)
|| levenshteinWeightedGeneric<UInt256>(columns, res_values)
|| levenshteinWeightedGeneric<Int8>(columns, res_values)
|| levenshteinWeightedGeneric<Int16>(columns, res_values)
|| levenshteinWeightedGeneric<Int32>(columns, res_values)
|| levenshteinWeightedGeneric<Int64>(columns, res_values)
|| levenshteinWeightedGeneric<Int128>(columns, res_values)
|| levenshteinWeightedGeneric<Int256>(columns, res_values)
|| levenshteinWeightedGeneric<Float32>(columns, res_values)
|| levenshteinWeightedGeneric<Float64>(columns, res_values)))
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unexpected code branch of function {}. No fitting levenshteinWeightedGeneric",
getName());
return;
}
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unexpected code branch of function {}. Wrong expected result type in levenshteinGeneric",
getName());
}
const ColumnArray * column_from = columns[0];
const ColumnArray * column_to = columns[1];
using ElementType = Result::Container::value_type;
for (size_t row = 0; row < column_from->size(); row++)
{
// Effective Levenshtein realization from Common/levenshteinDistance
Array from = (*column_from)[row].safeGet<Array>();
Array to = (*column_to)[row].safeGet<Array>();
res_values[row] = static_cast<ElementType>(levenshteinDistance<Field>(from, to));
}
}
template <typename N, typename W>
bool levenshteinWeightedString(VectorWithMemoryTracking<const ColumnArray *> columns, ColumnFloat64::Container & res_values) const
{
const N * from_data = checkAndGetColumn<N>(&columns[0]->getData());
const N * to_data = checkAndGetColumn<N>(&columns[1]->getData());
if (!from_data || !to_data)
return false;
const ColumnArray::Offsets & from_offsets = columns[0]->getOffsets();
ColumnArray::Offset prev_from_offset = 0;
const ColumnArray::Offsets & to_offsets = columns[1]->getOffsets();
ColumnArray::Offset prev_to_offset = 0;
const ColumnVector<W> * column_from_weights = checkAndGetColumn<ColumnVector<W>>(&columns[2]->getData());
const ColumnVector<W> * column_to_weights = checkAndGetColumn<ColumnVector<W>>(&columns[3]->getData());
if (!column_from_weights || !column_to_weights)
return false;
const ColumnArray::Offsets & from_weights_offsets = columns[2]->getOffsets();
ColumnArray::Offset prev_from_weights_offset = 0;
const ColumnArray::Offsets & to_weights_offsets = columns[3]->getOffsets();
ColumnArray::Offset prev_to_weights_offset = 0;
const auto extract_array = [](const N * data, size_t prev_offset, size_t count)
{
VectorWithMemoryTracking<std::string_view> temp;
temp.reserve(count);
for (size_t j = 0; j < count; ++j) { temp.emplace_back(data->getDataAt(prev_offset + j)); }
return temp;
};
for (size_t row = 0; row < columns[0]->size(); row++)
{
const size_t m = from_offsets[row] - prev_from_offset;
const size_t n = to_offsets[row] - prev_to_offset;
const VectorWithMemoryTracking<std::string_view> from = extract_array(from_data, prev_from_offset, m);
const VectorWithMemoryTracking<std::string_view> to = extract_array(to_data, prev_to_offset, n);
prev_from_offset = from_offsets[row];
prev_to_offset = to_offsets[row];
std::span<const W> from_weights(column_from_weights->getData().begin() + prev_from_weights_offset, from_weights_offsets[row] - prev_from_weights_offset);
prev_from_weights_offset = from_weights_offsets[row];
std::span<const W> to_weights(column_to_weights->getData().begin() + prev_to_weights_offset, to_weights_offsets[row] - prev_to_weights_offset);
prev_to_weights_offset = to_weights_offsets[row];
res_values[row] = static_cast<Float64>(DB::levenshteinDistanceWeighted<std::string_view, W>(from, to, from_weights, to_weights));
}
return true;
}
template <typename N, typename W>
bool levenshteinWeightedNumber(VectorWithMemoryTracking<const ColumnArray *> columns, ColumnFloat64::Container & res_values) const
{
const ColumnVectorOrDecimal<N> * column_from = checkAndGetColumn<ColumnVectorOrDecimal<N>>(&columns[0]->getData());
const ColumnVectorOrDecimal<N> * column_to = checkAndGetColumn<ColumnVectorOrDecimal<N>>(&columns[1]->getData());
if (!column_from || !column_to)
// just to be on the safe side, it's already checked
return false;
const ColumnArray::Offsets & from_offsets = columns[0]->getOffsets();
ColumnArray::Offset prev_from_offset = 0;
const ColumnArray::Offsets & to_offsets = columns[1]->getOffsets();
ColumnArray::Offset prev_to_offset = 0;
const ColumnVector<W> * column_from_weights = checkAndGetColumn<ColumnVector<W>>(&columns[2]->getData());
const ColumnVector<W> * column_to_weights = checkAndGetColumn<ColumnVector<W>>(&columns[3]->getData());
if (!column_from_weights || !column_to_weights)
return false;
const ColumnArray::Offsets & from_weights_offsets = columns[2]->getOffsets();
ColumnArray::Offset prev_from_weights_offset = 0;
const ColumnArray::Offsets & to_weights_offsets = columns[3]->getOffsets();
ColumnArray::Offset prev_to_weights_offset = 0;
for (size_t row = 0; row < columns[0]->size(); row++)
{
std::span<const N> from(column_from->getData().begin() + prev_from_offset, from_offsets[row] - prev_from_offset);
prev_from_offset = from_offsets[row];
std::span<const N> to(column_to->getData().begin() + prev_to_offset, to_offsets[row] - prev_to_offset);
prev_to_offset = to_offsets[row];
std::span<const W> from_weights(column_from_weights->getData().begin() + prev_from_weights_offset, from_weights_offsets[row] - prev_from_weights_offset);
prev_from_weights_offset = from_weights_offsets[row];
std::span<const W> to_weights(column_to_weights->getData().begin() + prev_to_weights_offset, to_weights_offsets[row] - prev_to_weights_offset);
prev_to_weights_offset = to_weights_offsets[row];
res_values[row] = static_cast<Float64>(DB::levenshteinDistanceWeighted<N, W>(from, to, from_weights, to_weights));
}
return true;
}
template<typename W>
bool levenshteinWeightedGeneric(VectorWithMemoryTracking<const ColumnArray *> columns, ColumnFloat64::Container & res_values) const
{
const ColumnArray * column_from = columns[0];
const ColumnArray * column_to = columns[1];
const ColumnVector<W> * column_from_weights = checkAndGetColumn<ColumnVector<W>>(&columns[2]->getData());
const ColumnVector<W> * column_to_weights = checkAndGetColumn<ColumnVector<W>>(&columns[3]->getData());
if (!column_from_weights || !column_to_weights)
return false;
const ColumnArray::Offsets & from_weights_offsets = columns[2]->getOffsets();
ColumnArray::Offset prev_from_weights_offset = 0;
const ColumnArray::Offsets & to_weights_offsets = columns[3]->getOffsets();
ColumnArray::Offset prev_to_weights_offset = 0;
for (size_t row = 0; row < column_from->size(); row++)
{
// Effective Levenshtein realization from Common/levenshteinDistance
Array from = (*column_from)[row].safeGet<Array>();
Array to = (*column_to)[row].safeGet<Array>();
std::span<const W> from_weights(column_from_weights->getData().begin() + prev_from_weights_offset, from_weights_offsets[row] - prev_from_weights_offset);
prev_from_weights_offset = from_weights_offsets[row];
std::span<const W> to_weights(column_to_weights->getData().begin() + prev_to_weights_offset, to_weights_offsets[row] - prev_to_weights_offset);
prev_to_weights_offset = to_weights_offsets[row];
res_values[row] = static_cast<Float64>(DB::levenshteinDistanceWeighted<Field, W>(from, to, from_weights, to_weights));
}
return true;
}
template <typename ResultColumn, typename... Types>
bool tryLevenshteinNumber(VectorWithMemoryTracking<const ColumnArray *> columns, ResultColumn::Container & res_values) const
{
return (levenshteinNumber<Types, ResultColumn>(columns, res_values) || ...);
}
template <typename ResultColumn, typename... Types>
bool tryLevenshteinString(VectorWithMemoryTracking<const ColumnArray *> columns, ResultColumn::Container & res_values) const
{
return (levenshteinString<Types, ResultColumn>(columns, res_values) || ...);
}
ColumnPtr levenshteinImpl(VectorWithMemoryTracking<const ColumnArray *> columns) const
{
auto res = ColumnUInt32::create();
ColumnUInt32::Container & res_values = res->getData();
res_values.resize(columns[0]->size());
if (tryLevenshteinNumber<
ColumnUInt32,
UInt8,
UInt16,
UInt32,
UInt64,
UInt128,
UInt256,
Int8,
Int16,
Int32,
Int64,
Int128,
Int256,
Float32,
Float64,
Decimal32,
Decimal64,
Decimal128,
Decimal256,
DateTime64>(columns, res_values)
|| tryLevenshteinString<ColumnUInt32, ColumnString, ColumnFixedString>(columns, res_values))
return res;
levenshteinGeneric<ColumnUInt32>(columns, res_values);
return res;
}
ColumnPtr weightedLevenshteinImpl(VectorWithMemoryTracking<const ColumnArray *> columns) const
{
for (size_t i = 0; i < 2; i++)
{
const ColumnArray * hs_column = columns[i];
const ColumnArray * weights_column = columns[i+2];
for (size_t row = 0; row < hs_column->size(); row++)
{
Array hs = (*hs_column)[row].safeGet<Array>();
Array weights = (*weights_column)[row].safeGet<Array>();
if (hs.size() != weights.size())
throw Exception(
ErrorCodes::SIZES_OF_ARRAYS_DONT_MATCH,
"Arguments {} ({}, size {}) and {} ({}, size {}) of function {} must be arrays of the same size",
toString(i + 1),
hs_column->getName(),
hs.size(),
toString(i + 3),
weights_column->getName(),
weights.size(),
getName());
}
}
auto res = ColumnFloat64::create();
ColumnFloat64::Container & res_values = res->getData();
res_values.resize(columns[0]->size());
if (tryLevenshteinNumber<
ColumnFloat64,
UInt8,
UInt16,
UInt32,
UInt64,
UInt128,
UInt256,
Int8,
Int16,
Int32,
Int64,
Int128,
Int256,
Float32,
Float64,
Decimal32,
Decimal64,
Decimal128,
Decimal256,
DateTime64>(columns, res_values)
|| tryLevenshteinString<ColumnFloat64, ColumnString, ColumnFixedString>(columns, res_values))
return res;
levenshteinGeneric<ColumnFloat64>(columns, res_values);
return res;
}
template <typename W>
bool similarity(VectorWithMemoryTracking<const ColumnArray *> columns, ColumnPtr distance, ColumnFloat64::Container & res_values) const
{
const ColumnVector<W> * column_from_weights = checkAndGetColumn<ColumnVector<W>>(&columns[2]->getData());
const ColumnVector<W> * column_to_weights = checkAndGetColumn<ColumnVector<W>>(&columns[3]->getData());
if (!column_from_weights || !column_to_weights)
return false;
const ColumnArray::Offsets & from_weights_offsets = columns[2]->getOffsets();
ColumnArray::Offset prev_from_weights_offset = 0;
const ColumnArray::Offsets & to_weights_offsets = columns[3]->getOffsets();
ColumnArray::Offset prev_to_weights_offset = 0;
for (size_t row = 0; row < distance->size(); row++)
{
std::span<const W> from_weights(column_from_weights->getData().begin() + prev_from_weights_offset, from_weights_offsets[row] - prev_from_weights_offset);
prev_from_weights_offset = from_weights_offsets[row];
std::span<const W> to_weights(column_to_weights->getData().begin() + prev_to_weights_offset, to_weights_offsets[row] - prev_to_weights_offset);
prev_to_weights_offset = to_weights_offsets[row];
if (distance->getFloat64(row) == 0)
{
res_values[row] = 1.0;
continue;
}
// Sum the weights in a wide accumulator (exact for integral weights, no overflow/UB), then
// convert once to Float64 to match the distance domain. Mirrors levenshteinDistanceWeighted.
using Acc = LevenshteinWeightAccumulator<W>;
Acc weights_acc = 0;
for (const auto & weight : from_weights)
weights_acc += static_cast<Acc>(weight);
for (const auto & weight : to_weights)
weights_acc += static_cast<Acc>(weight);
const Float64 weights_sum = static_cast<Float64>(weights_acc);
if (weights_sum == 0)
{
res_values[row] = 1.0;
continue;
}
res_values[row] = 1.0 - (distance->getFloat64(row) / weights_sum);
}
return true;
}
};
struct SimpleLevenshtein
{
static constexpr auto name{"arrayLevenshteinDistance"};
static constexpr size_t arguments = 2;
};
template <>
DataTypePtr FunctionArrayLevenshtein<SimpleLevenshtein>::getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const
{
FunctionArgumentDescriptors args_descriptors;
args_descriptors = FunctionArgumentDescriptors{
{"from", static_cast<FunctionArgumentDescriptor::TypeValidator>(&isArray), nullptr, "Array"},
{"to", static_cast<FunctionArgumentDescriptor::TypeValidator>(&isArray), nullptr, "Array"},
};
validateFunctionArguments(*this, arguments, args_descriptors);
return std::make_shared<DataTypeUInt32>();
}
template <>
ColumnPtr FunctionArrayLevenshtein<SimpleLevenshtein>::execute(VectorWithMemoryTracking<const ColumnArray *> columns) const
{
return levenshteinImpl(columns);
}
struct Weighted
{
static constexpr auto name{"arrayLevenshteinDistanceWeighted"};
static constexpr size_t arguments = 4;
};
template <>
ColumnPtr FunctionArrayLevenshtein<Weighted>::execute(VectorWithMemoryTracking<const ColumnArray *> columns) const
{
return weightedLevenshteinImpl(columns);
}
struct Similarity
{
static constexpr auto name{"arraySimilarity"};
static constexpr size_t arguments = 4;
};
template <>
ColumnPtr FunctionArrayLevenshtein<Similarity>::execute(VectorWithMemoryTracking<const ColumnArray *> columns) const
{
ColumnPtr distance = weightedLevenshteinImpl(columns);
auto result = ColumnFloat64::create();
ColumnFloat64::Container & res_values = result->getData();
res_values.resize(distance->size());
if (!(
similarity<UInt8>(columns, distance, res_values) || similarity<UInt16>(columns, distance, res_values)
|| similarity<UInt32>(columns, distance, res_values) || similarity<UInt64>(columns, distance, res_values)
|| similarity<UInt128>(columns, distance, res_values) || similarity<UInt256>(columns, distance, res_values)
|| similarity<Int8>(columns, distance, res_values) || similarity<Int16>(columns, distance, res_values)
|| similarity<Int32>(columns, distance, res_values) || similarity<Int64>(columns, distance, res_values)
|| similarity<Int128>(columns, distance, res_values) || similarity<Int256>(columns, distance, res_values)
|| similarity<Float32>(columns, distance, res_values) || similarity<Float64>(columns, distance, res_values)))
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Unexpected code branch of function {}. No matching column types for {} and {}",
getName(),
columns[2]->getName(),
columns[3]->getName());
return result;
}
REGISTER_FUNCTION(ArrayLevenshtein)
{
FunctionDocumentation::Description description_arrayLevDis = "Calculates the Levenshtein distance for two arrays.";
FunctionDocumentation::Syntax syntax_arrayLevDis = "arrayLevenshteinDistance(from, to)";
FunctionDocumentation::Arguments arguments_arrayLevDis = {
{"from", "The first array. [`Array(T)`](/reference/data-types/array)."},
{"to", "The second array. [`Array(T)`](/reference/data-types/array)."}
};
FunctionDocumentation::ReturnedValue returned_value_arrayLevDis = {"Levenshtein distance between the first and the second arrays.", {"Float64"}};
FunctionDocumentation::Examples example_arrayLevDis = {
{
"Usage example",
"SELECT arrayLevenshteinDistance([1, 2, 4], [1, 2, 3])",
"1"
}
};
FunctionDocumentation::IntroducedIn introduced_in_arrayLevDis = {25, 4};
FunctionDocumentation::Category category_arrayLevDis = FunctionDocumentation::Category::Array;
FunctionDocumentation documentation_arrayLevDis = {description_arrayLevDis, syntax_arrayLevDis, arguments_arrayLevDis, {}, returned_value_arrayLevDis, example_arrayLevDis, introduced_in_arrayLevDis, category_arrayLevDis};
factory.registerFunction<FunctionArrayLevenshtein<SimpleLevenshtein>>(documentation_arrayLevDis);
FunctionDocumentation::Description description_arrayLevDisW = R"(
Calculates Levenshtein distance for two arrays with custom weights for each element.
The number of elements for the array and its weights should match.
)";
FunctionDocumentation::Syntax syntax_arrayLevDisW = "arrayLevenshteinDistanceWeighted(from, to, from_weights, to_weights)";
FunctionDocumentation::Arguments arguments_arrayLevDisW = {
{"from", "first array. [`Array(T)`](/reference/data-types/array)."},
{"to", "second array. [`Array(T)`](/reference/data-types/array)."},
{"from_weights", "weights for the first array.", {"Array((U)Int*|Float*)"}},
{"to_weights", "weights for the second array.", {"Array((U)Int*|Float*)"}},
};
FunctionDocumentation::ReturnedValue returned_value_arrayLevDisW = {"Levenshtein distance between the first and the second arrays with custom weights for each element", {"Float64"}};
FunctionDocumentation::IntroducedIn introduced_in_arrayLevDisW = {25, 4};
FunctionDocumentation::Examples examples_arrayLevDisW = {
{
"Usage example",
"SELECT arrayLevenshteinDistanceWeighted(['A', 'B', 'C'], ['A', 'K', 'L'], [1.0, 2, 3], [3.0, 4, 5])",
"14"
}
};
FunctionDocumentation::Category category_arrayLevDisW = FunctionDocumentation::Category::Array;
FunctionDocumentation documentation_arrayLevDisW = {description_arrayLevDisW, syntax_arrayLevDisW, arguments_arrayLevDisW, {}, returned_value_arrayLevDisW, examples_arrayLevDisW, introduced_in_arrayLevDisW, category_arrayLevDisW};
factory.registerFunction<FunctionArrayLevenshtein<Weighted>>(documentation_arrayLevDisW);
FunctionDocumentation::Description description_arraySim = R"(
Calculates the similarity of two arrays from `0` to `1` based on weighted Levenshtein distance.
)";
FunctionDocumentation::Syntax syntax_arraySim = "arraySimilarity(from, to, from_weights, to_weights)";
FunctionDocumentation::Arguments arguments_arraySim = {
{"from", "first array", {"Array(T)"}},
{"to", "second array", {"Array(T)"}},
{"from_weights", "weights for the first array.", {"Array((U)Int*|Float*)"}},
{"to_weights", "weights for the second array.", {"Array((U)Int*|Float*)"}},
};
FunctionDocumentation::ReturnedValue returned_value_arraySim = {"Returns the similarity between `0` and `1` of the two arrays based on the weighted Levenshtein distance", {"Float64"}};
FunctionDocumentation::Examples examples_arraySim =
{
{
"Usage example",
"SELECT arraySimilarity(['A', 'B', 'C'], ['A', 'K', 'L'], [1.0, 2, 3], [3.0, 4, 5]);",
"0.2222222222222222"
}
};
FunctionDocumentation::IntroducedIn introduced_in_arraySim = {25, 4};
FunctionDocumentation::Category category_arraySim = FunctionDocumentation::Category::Array;
FunctionDocumentation documentation_arraySim = {description_arraySim, syntax_arraySim, arguments_arraySim, {}, returned_value_arraySim, examples_arraySim, introduced_in_arraySim, category_arraySim};
factory.registerFunction<FunctionArrayLevenshtein<Similarity>>(documentation_arraySim);
}
}