thing-matcher 0.5.0

Deterministic and probabilistic matching of schema.org Thing records (name, alternateName, description, identifier, url, sameAs, additionalType) with explainable per-field score breakdowns.
Documentation
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
//! Data models for things, aligned with `schema.org/Thing`.
//!
//! This module is intentionally **logic-free**: it defines the types that
//! flow through the matching engine but contains no matching code itself.
//! See [`crate::matcher`] for the engine and [`crate::normalizer`] for the
//! text transformations that the matcher applies to these fields.
//!
//! All public types here are `Serialize + Deserialize` so they round-trip
//! through JSON, MessagePack, or any other `serde` format.
//!
//! ## Schema.org alignment
//!
//! The fields of [`Thing`] correspond to the properties of
//! `schema.org/Thing`:
//!
//! | Rust field | schema.org property |
//! |---|---|
//! | `name` | `name` |
//! | `alternate_names` | `alternateName` |
//! | `description` | `description` |
//! | `disambiguating_description` | `disambiguatingDescription` |
//! | `identifiers` | `identifier` (as `PropertyValue`) |
//! | `url` | `url` |
//! | `image` | `image` |
//! | `same_as` | `sameAs` |
//! | `main_entity_of_page` | `mainEntityOfPage` |
//! | `additional_types` | `additionalType` |
//! | `subject_of` | `subjectOf` |
//! | `owner` | `owner` |
//!
//! ## Building a thing
//!
//! Prefer [`Thing::builder`] over constructing the struct literal — the
//! builder accepts `impl Into<String>` so call-sites can pass `&str`,
//! `String`, or owned values interchangeably.
//!
//! ```
//! use thing_matcher::Thing;
//!
//! let t = Thing::builder()
//!     .name("Eiffel Tower")
//!     .add_alternate_name("La Tour Eiffel")
//!     .url("https://www.toureiffel.paris/")
//!     .build();
//!
//! assert_eq!(t.name.as_deref(), Some("Eiffel Tower"));
//! ```

use serde::{Deserialize, Serialize};

/// External identifier for a thing, modelled on `schema.org/PropertyValue`.
///
/// Two `Identifier` values are equal iff both their `property_id` and their
/// `value` are equal. Equality is structural — no per-scheme
/// canonicalisation is performed.
///
/// `property_id` is the issuer or vocabulary that names the identifier,
/// such as `"wikidata"`, `"isbn"`, `"doi"`, `"gtin"`, or a fully-qualified
/// URL. `value` is the identifier string itself.
///
/// # Example
///
/// ```
/// use thing_matcher::Identifier;
///
/// let a = Identifier::new("wikidata", "Q243").unwrap();
/// let b = Identifier::new("wikidata", " Q243 ").unwrap();
/// assert_eq!(a, b, "values are trimmed at construction");
/// assert!(Identifier::new("wikidata", "").is_none());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Identifier {
    /// Issuer or vocabulary that scopes the identifier, e.g.
    /// `"wikidata"`, `"isbn"`, `"doi"`, `"gtin"`, or a URL.
    pub property_id: String,
    /// The identifier value, trimmed of surrounding whitespace.
    pub value: String,
}

impl Identifier {
    /// Construct an [`Identifier`], trimming the value and property id of
    /// surrounding whitespace. Returns `None` if either trimmed component
    /// is empty.
    ///
    /// No further normalisation is applied — different vocabularies have
    /// different rules and the crate makes no assumptions.
    ///
    /// # Example
    ///
    /// ```
    /// use thing_matcher::Identifier;
    ///
    /// let id = Identifier::new("wikidata", "  Q243  ").unwrap();
    /// assert_eq!(id.value, "Q243");
    /// assert_eq!(id.property_id, "wikidata");
    ///
    /// assert!(Identifier::new("wikidata", "   ").is_none());
    /// assert!(Identifier::new("   ", "Q243").is_none());
    /// ```
    pub fn new(property_id: impl Into<String>, value: impl Into<String>) -> Option<Self> {
        let property_id = property_id.into().trim().to_string();
        let value = value.into().trim().to_string();
        if property_id.is_empty() || value.is_empty() {
            None
        } else {
            Some(Self { property_id, value })
        }
    }
}

/// Core data structure for a thing, aligned with `schema.org/Thing`.
///
/// Every field is optional (or defaults to empty). The matcher tolerates
/// missing data field-by-field — a `None` value never penalises a thing.
/// See [`crate::matcher::MatchingEngine::match_things`] for how missing
/// fields affect the weighted score.
///
/// Construct via [`Thing::builder`] rather than struct literal syntax so
/// the call-site stays compact and forward-compatible if fields are added.
///
/// # Example
///
/// ```
/// use thing_matcher::Thing;
///
/// let t = Thing::builder()
///     .name("Eiffel Tower")
///     .add_alternate_name("La Tour Eiffel")
///     .description("Wrought-iron lattice tower on the Champ de Mars in Paris.")
///     .url("https://www.toureiffel.paris/")
///     .build();
///
/// assert_eq!(t.name.as_deref(), Some("Eiffel Tower"));
/// assert_eq!(t.alternate_names, vec!["La Tour Eiffel".to_string()]);
/// ```
///
/// `Thing` round-trips through `serde`.
///
/// ```
/// # use thing_matcher::Thing;
/// let t = Thing::builder().name("Eiffel Tower").build();
/// let json = serde_json::to_string(&t).unwrap();
/// let back: Thing = serde_json::from_str(&json).unwrap();
/// assert_eq!(t, back);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Thing {
    /// Primary canonical name. Corresponds to `schema.org/name`.
    pub name: Option<String>,

    /// Aliases, endonyms, or translations. Corresponds to
    /// `schema.org/alternateName`. The matcher takes the best score
    /// across the cartesian product of primary + alternates.
    pub alternate_names: Vec<String>,

    /// Free-form description. Corresponds to `schema.org/description`.
    pub description: Option<String>,

    /// Short disambiguating description. Corresponds to
    /// `schema.org/disambiguatingDescription`.
    pub disambiguating_description: Option<String>,

    /// Scheme-scoped external identifiers. Corresponds to
    /// `schema.org/identifier` modelled as `PropertyValue`. Sharing any
    /// one `(property_id, value)` pair across two things is a
    /// deterministic match.
    pub identifiers: Vec<Identifier>,

    /// Canonical URL of the item. Corresponds to `schema.org/url`.
    pub url: Option<String>,

    /// URL of a representative image. Corresponds to `schema.org/image`.
    pub image: Option<String>,

    /// Reference URLs that unambiguously indicate the same item, e.g. a
    /// Wikipedia article or an authority record. Corresponds to
    /// `schema.org/sameAs`.
    pub same_as: Vec<String>,

    /// Page (URL) for which this thing is the main entity. Corresponds
    /// to `schema.org/mainEntityOfPage`.
    pub main_entity_of_page: Option<String>,

    /// Additional types from external vocabularies, typically schema.org
    /// subtypes or other ontology URIs. Corresponds to
    /// `schema.org/additionalType`.
    pub additional_types: Vec<String>,

    /// Works or events about this thing (URLs). Corresponds to
    /// `schema.org/subjectOf`.
    pub subject_of: Vec<String>,

    /// Person or organisation that owns this thing. Corresponds to
    /// `schema.org/owner`. Stored as a string (a name or URL) — the
    /// crate does not model `Person` / `Organization` separately.
    pub owner: Option<String>,

    /// Local identifier issued by the originating system. Not
    /// normalised, not scored — different organisations may issue
    /// colliding values. Kept for round-trip honesty.
    pub local_id: Option<String>,
}

impl Thing {
    /// Begin constructing a [`Thing`] with the [`ThingBuilder`].
    ///
    /// All fields default to `None` / empty until a setter is called.
    ///
    /// # Example
    ///
    /// ```
    /// use thing_matcher::Thing;
    ///
    /// let t = Thing::builder()
    ///     .name("Big Ben")
    ///     .build();
    ///
    /// assert_eq!(t.name.as_deref(), Some("Big Ben"));
    /// ```
    pub fn builder() -> ThingBuilder {
        ThingBuilder::default()
    }

    /// Validate that the thing carries a primary name.
    ///
    /// Returns `Ok(())` if `name` is set. Otherwise returns
    /// [`crate::MatchingError::MissingField`].
    ///
    /// This is **not** invoked automatically by the matcher — call it at
    /// the system boundary when you ingest data, not on every
    /// comparison.
    ///
    /// # Example
    ///
    /// ```
    /// use thing_matcher::Thing;
    ///
    /// assert!(Thing::builder().name("Eiffel Tower").build().validate().is_ok());
    /// assert!(Thing::builder().build().validate().is_err());
    /// ```
    pub fn validate(&self) -> crate::Result<()> {
        if self.name.is_none() {
            return Err(crate::MatchingError::MissingField(
                "name is required".to_string(),
            ));
        }
        Ok(())
    }
}

/// Fluent builder for [`Thing`].
///
/// All string setters accept `impl Into<String>` so call-sites may pass
/// `&str`, `String`, or `&String` interchangeably without explicit
/// conversion.
///
/// # Example
///
/// ```
/// use thing_matcher::{Thing, ThingBuilder};
///
/// let t: Thing = ThingBuilder::default()
///     .name(String::from("Eiffel Tower"))
///     .add_alternate_name("La Tour Eiffel")
///     .url("https://www.toureiffel.paris/")
///     .add_same_as("https://www.wikidata.org/wiki/Q243")
///     .build();
///
/// assert_eq!(t.name.as_deref(), Some("Eiffel Tower"));
/// assert_eq!(t.same_as.len(), 1);
/// ```
#[derive(Default)]
pub struct ThingBuilder {
    name: Option<String>,
    alternate_names: Vec<String>,
    description: Option<String>,
    disambiguating_description: Option<String>,
    identifiers: Vec<Identifier>,
    url: Option<String>,
    image: Option<String>,
    same_as: Vec<String>,
    main_entity_of_page: Option<String>,
    additional_types: Vec<String>,
    subject_of: Vec<String>,
    owner: Option<String>,
    local_id: Option<String>,
}

impl ThingBuilder {
    /// Set the primary canonical name.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder().name("Eiffel Tower").build();
    /// assert_eq!(t.name.as_deref(), Some("Eiffel Tower"));
    /// ```
    pub fn name<S: Into<String>>(mut self, value: S) -> Self {
        self.name = Some(value.into());
        self
    }

    /// Replace the entire list of alternate names.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder()
    ///     .alternate_names(vec!["La Tour Eiffel".into(), "Tour Eiffel".into()])
    ///     .build();
    /// assert_eq!(t.alternate_names.len(), 2);
    /// ```
    pub fn alternate_names(mut self, value: Vec<String>) -> Self {
        self.alternate_names = value;
        self
    }

    /// Append a single alternate name.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder()
    ///     .add_alternate_name("La Tour Eiffel")
    ///     .add_alternate_name("Tour Eiffel")
    ///     .build();
    /// assert_eq!(t.alternate_names.len(), 2);
    /// ```
    pub fn add_alternate_name<S: Into<String>>(mut self, value: S) -> Self {
        self.alternate_names.push(value.into());
        self
    }

    /// Set the free-form description.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder().description("A landmark in Paris.").build();
    /// assert_eq!(t.description.as_deref(), Some("A landmark in Paris."));
    /// ```
    pub fn description<S: Into<String>>(mut self, value: S) -> Self {
        self.description = Some(value.into());
        self
    }

    /// Set the disambiguating description.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder().disambiguating_description("The Paris one.").build();
    /// assert_eq!(t.disambiguating_description.as_deref(), Some("The Paris one."));
    /// ```
    pub fn disambiguating_description<S: Into<String>>(mut self, value: S) -> Self {
        self.disambiguating_description = Some(value.into());
        self
    }

    /// Replace the entire list of identifiers.
    ///
    /// ```
    /// # use thing_matcher::{Thing, Identifier};
    /// let id = Identifier::new("wikidata", "Q243").unwrap();
    /// let t = Thing::builder().identifiers(vec![id.clone()]).build();
    /// assert_eq!(t.identifiers, vec![id]);
    /// ```
    pub fn identifiers(mut self, value: Vec<Identifier>) -> Self {
        self.identifiers = value;
        self
    }

    /// Append a single identifier.
    ///
    /// ```
    /// # use thing_matcher::{Thing, Identifier};
    /// let t = Thing::builder()
    ///     .add_identifier(Identifier::new("wikidata", "Q243").unwrap())
    ///     .build();
    /// assert_eq!(t.identifiers.len(), 1);
    /// ```
    pub fn add_identifier(mut self, value: Identifier) -> Self {
        self.identifiers.push(value);
        self
    }

    /// Set the canonical URL.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder().url("https://www.toureiffel.paris/").build();
    /// assert_eq!(t.url.as_deref(), Some("https://www.toureiffel.paris/"));
    /// ```
    pub fn url<S: Into<String>>(mut self, value: S) -> Self {
        self.url = Some(value.into());
        self
    }

    /// Set the representative image URL.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder().image("https://example.org/eiffel.jpg").build();
    /// assert_eq!(t.image.as_deref(), Some("https://example.org/eiffel.jpg"));
    /// ```
    pub fn image<S: Into<String>>(mut self, value: S) -> Self {
        self.image = Some(value.into());
        self
    }

    /// Replace the entire `sameAs` list.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder()
    ///     .same_as(vec![
    ///         "https://www.wikidata.org/wiki/Q243".into(),
    ///         "https://en.wikipedia.org/wiki/Eiffel_Tower".into(),
    ///     ])
    ///     .build();
    /// assert_eq!(t.same_as.len(), 2);
    /// ```
    pub fn same_as(mut self, value: Vec<String>) -> Self {
        self.same_as = value;
        self
    }

    /// Append a single `sameAs` URL.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder()
    ///     .add_same_as("https://www.wikidata.org/wiki/Q243")
    ///     .build();
    /// assert_eq!(t.same_as.len(), 1);
    /// ```
    pub fn add_same_as<S: Into<String>>(mut self, value: S) -> Self {
        self.same_as.push(value.into());
        self
    }

    /// Set the `mainEntityOfPage` URL.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder()
    ///     .main_entity_of_page("https://en.wikipedia.org/wiki/Eiffel_Tower")
    ///     .build();
    /// assert_eq!(
    ///     t.main_entity_of_page.as_deref(),
    ///     Some("https://en.wikipedia.org/wiki/Eiffel_Tower"),
    /// );
    /// ```
    pub fn main_entity_of_page<S: Into<String>>(mut self, value: S) -> Self {
        self.main_entity_of_page = Some(value.into());
        self
    }

    /// Replace the entire list of `additionalType` URIs.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder()
    ///     .additional_types(vec!["https://schema.org/Landmark".into()])
    ///     .build();
    /// assert_eq!(t.additional_types.len(), 1);
    /// ```
    pub fn additional_types(mut self, value: Vec<String>) -> Self {
        self.additional_types = value;
        self
    }

    /// Append a single `additionalType` URI.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder()
    ///     .add_additional_type("https://schema.org/Landmark")
    ///     .build();
    /// assert_eq!(t.additional_types.len(), 1);
    /// ```
    pub fn add_additional_type<S: Into<String>>(mut self, value: S) -> Self {
        self.additional_types.push(value.into());
        self
    }

    /// Replace the entire `subjectOf` list.
    pub fn subject_of(mut self, value: Vec<String>) -> Self {
        self.subject_of = value;
        self
    }

    /// Append a single `subjectOf` URL.
    pub fn add_subject_of<S: Into<String>>(mut self, value: S) -> Self {
        self.subject_of.push(value.into());
        self
    }

    /// Set the owner (person or organisation, as a string).
    pub fn owner<S: Into<String>>(mut self, value: S) -> Self {
        self.owner = Some(value.into());
        self
    }

    /// Set the local identifier.
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder().local_id("REF-12345").build();
    /// assert_eq!(t.local_id.as_deref(), Some("REF-12345"));
    /// ```
    pub fn local_id<S: Into<String>>(mut self, value: S) -> Self {
        self.local_id = Some(value.into());
        self
    }

    /// Consume the builder and produce the [`Thing`].
    ///
    /// ```
    /// # use thing_matcher::Thing;
    /// let t = Thing::builder().name("Big Ben").build();
    /// assert!(t.url.is_none());
    /// ```
    pub fn build(self) -> Thing {
        Thing {
            name: self.name,
            alternate_names: self.alternate_names,
            description: self.description,
            disambiguating_description: self.disambiguating_description,
            identifiers: self.identifiers,
            url: self.url,
            image: self.image,
            same_as: self.same_as,
            main_entity_of_page: self.main_entity_of_page,
            additional_types: self.additional_types,
            subject_of: self.subject_of,
            owner: self.owner,
            local_id: self.local_id,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn thing_builder_starts_empty() {
        let t = Thing::builder().build();
        assert!(t.name.is_none());
        assert!(t.alternate_names.is_empty());
        assert!(t.description.is_none());
        assert!(t.disambiguating_description.is_none());
        assert!(t.identifiers.is_empty());
        assert!(t.url.is_none());
        assert!(t.image.is_none());
        assert!(t.same_as.is_empty());
        assert!(t.main_entity_of_page.is_none());
        assert!(t.additional_types.is_empty());
        assert!(t.subject_of.is_empty());
        assert!(t.owner.is_none());
        assert!(t.local_id.is_none());
    }

    #[test]
    fn thing_builder_accepts_str_and_string() {
        let t = Thing::builder()
            .name("Eiffel Tower")
            .add_alternate_name(String::from("La Tour Eiffel"))
            .build();
        assert_eq!(t.name.as_deref(), Some("Eiffel Tower"));
        assert_eq!(t.alternate_names, vec!["La Tour Eiffel".to_string()]);
    }

    #[test]
    fn thing_validate_requires_a_name() {
        assert!(
            Thing::builder()
                .name("Eiffel Tower")
                .build()
                .validate()
                .is_ok()
        );
        let err = Thing::builder()
            .build()
            .validate()
            .expect_err("should be missing");
        assert!(matches!(err, crate::MatchingError::MissingField(_)));
    }

    #[test]
    fn thing_round_trips_through_serde() {
        let t = Thing::builder()
            .name("Eiffel Tower")
            .add_alternate_name("La Tour Eiffel")
            .description("Iron tower in Paris.")
            .url("https://www.toureiffel.paris/")
            .add_identifier(Identifier::new("wikidata", "Q243").unwrap())
            .add_same_as("https://www.wikidata.org/wiki/Q243")
            .add_additional_type("https://schema.org/Landmark")
            .build();
        let json = serde_json::to_string(&t).expect("serialise");
        let back: Thing = serde_json::from_str(&json).expect("deserialise");
        assert_eq!(t, back);
    }

    #[test]
    fn alternate_names_setter_replaces_vec() {
        let t = Thing::builder()
            .alternate_names(vec!["X".into(), "Y".into()])
            .build();
        assert_eq!(t.alternate_names, vec!["X".to_string(), "Y".to_string()]);
    }

    #[test]
    fn identifier_trims_value_and_property_id() {
        let id = Identifier::new("  wikidata  ", "   Q243 ").unwrap();
        assert_eq!(id.property_id, "wikidata");
        assert_eq!(id.value, "Q243");
    }

    #[test]
    fn identifier_rejects_empty_components() {
        assert!(Identifier::new("wikidata", "").is_none());
        assert!(Identifier::new("wikidata", "    ").is_none());
        assert!(Identifier::new("", "Q243").is_none());
        assert!(Identifier::new("   ", "Q243").is_none());
    }

    #[test]
    fn identifier_equality_is_property_scoped() {
        let g = Identifier::new("google", "X").unwrap();
        let w = Identifier::new("wikidata", "X").unwrap();
        assert_ne!(g, w);
    }

    #[test]
    fn identifier_round_trips_through_serde() {
        let id = Identifier::new("custom", "abc-123").unwrap();
        let json = serde_json::to_string(&id).expect("serialise");
        let back: Identifier = serde_json::from_str(&json).expect("deserialise");
        assert_eq!(id, back);
    }
}