class ContextualEntityRuler extends AnnotatorModel[ContextualEntityRuler] with HasSimpleAnnotate[ContextualEntityRuler] with HandleExceptionParams with HasSafeAnnotate[ContextualEntityRuler] with CheckLicense

ContextualEntityRuler is an annotator that updates chunks based on contextual rules. These rules are defined in the ContextualEntityRulerRules class and can include prefixes, suffixes, and the context within a specified scope window around the chunk.

This annotator modifies the detected chunks by replacing their entity labels or content based on matching patterns and rules. It is particularly useful for refining entity recognition results in domain-specific text processing.

Example

Define pipeline stages to extract entities:

val documentAssembler = new DocumentAssembler()
  .setInputCol("text")
  .setOutputCol("document")

val sentenceDetector = new SentenceDetector()
  .setInputCols("document")
  .setOutputCol("sentences")

val tokenizer = new Tokenizer()
  .setInputCols("sentences")
  .setOutputCol("tokens")

val embeddings = WordEmbeddingsModel
  .pretrained("embeddings_clinical", "en", "clinical/models")
  .setInputCols("sentences", "tokens")
  .setOutputCol("embeddings")

val medicalNerModel = MedicalNerModel
  .pretrained("ner_deid_generic_augmented", "en", "clinical/models")
  .setInputCols("sentences", "tokens", "embeddings")
  .setOutputCol("ner")

val nerChunks = new NerConverterInternal()
  .setInputCols("sentences", "tokens", "ner")
  .setOutputCol("nerChunks")

Define ContextualEntityRuler and set the rules:

val jsonRules =
  """
    |[{
    | "entity" : "AGE",
    | "scopeWindow" : [2, 2],
    | "scopeWindowLevel" : "token",
    | "prefixPatterns" : ["is"],
    | "suffixPatterns" : ["years"],
    | "replaceEntity" : "REPLACED_AGE"
    | }]
    |""".stripMargin

val contextualEntityRuler = new ContextualEntityRuler()
  .setInputCols(Array("sentences", "tokens", "nerChunks"))
  .setOutputCol("updated_chunks")
  .setRulesAsStr(jsonRules)
  .setCaseSensitive(false)
  .setAllowPunctuationInBetween(true)

val pipeline = new Pipeline().setStages(
  Array(
    documentAssembler,
    sentenceDetector,
    tokenizer,
    embeddings,
    medicalNerModel,
    nerChunks,
    contextualEntityRuler
  ))

val result = pipeline
  .fit(Seq.empty[String].toDF("text"))
  .transform(Seq(
    "California, known for its beautiful beaches, and he is 36 years old. " +
    "The Grand Canyon in Arizona, where the age is, 37, is a stunning natural landmark. " +
    "It was founded on September 9, 1850, and Arizona on February 14, 1912."
  ).toDF("text"))

Show results:

result.selectExpr("explode(updated_chunks) as filtered").show(100, truncate = false)

// Example output:

 +-----------------+-----+---+--------+
  |result           |begin|end|entity  |
  +-----------------+-----+---+--------+
  |California       |0    |9  |LOCATION|
  |is 36 years      |52   |62 |AGE     |
  |Grand Canyon     |73   |84 |LOCATION|
  |Arizona          |89   |95 |LOCATION|
  |is, 37           |112  |117|AGE     |
  |September 9, 1850|170  |186|DATE    |
  |February 14, 1912|204  |220|DATE    |
  +-----------------+-----+---+--------+

Key Concepts

  • **Rules**: Define the contextual rules in JSON format, specifying:
    • entity: The target entity to match (e.g., AGE).
    • scopeWindow: A range [x, y] defining the number of tokens around the entity to consider.
    • scopeWindowLevel: The level of the scope window (token or char).
    • prefixPatterns: Patterns to match before the entity (e.g., "is").
    • suffixPatterns: Patterns to match after the entity (e.g., "years").
    • prefixRegexes: Regular expressions to match before the entity.
    • suffixRegexes: Regular expressions to match after the entity.
    • replaceEntity: The value to replace the matched entity with.
    • mode: The mode of the rule. It can be either "include" or "exclude".
  • **Parameters**:
    • setCaseSensitive: Enables case sensitivity in pattern matching.
    • setAllowPunctuationInBetween: Allows punctuation to appear between matched patterns and entities. -
Linear Supertypes
CheckLicense, HasSafeAnnotate[ContextualEntityRuler], HandleExceptionParams, HasSimpleAnnotate[ContextualEntityRuler], AnnotatorModel[ContextualEntityRuler], CanBeLazy, RawAnnotator[ContextualEntityRuler], HasOutputAnnotationCol, HasInputAnnotationCols, HasOutputAnnotatorType, ParamsAndFeaturesWritable, HasFeatures, DefaultParamsWritable, MLWritable, Model[ContextualEntityRuler], Transformer, PipelineStage, Logging, Params, Serializable, Serializable, Identifiable, AnyRef, Any
Ordering
  1. Grouped
  2. Alphabetic
  3. By Inheritance
Inherited
  1. ContextualEntityRuler
  2. CheckLicense
  3. HasSafeAnnotate
  4. HandleExceptionParams
  5. HasSimpleAnnotate
  6. AnnotatorModel
  7. CanBeLazy
  8. RawAnnotator
  9. HasOutputAnnotationCol
  10. HasInputAnnotationCols
  11. HasOutputAnnotatorType
  12. ParamsAndFeaturesWritable
  13. HasFeatures
  14. DefaultParamsWritable
  15. MLWritable
  16. Model
  17. Transformer
  18. PipelineStage
  19. Logging
  20. Params
  21. Serializable
  22. Serializable
  23. Identifiable
  24. AnyRef
  25. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Instance Constructors

  1. new ContextualEntityRuler()
  2. new ContextualEntityRuler(uid: String)

    uid

    a unique identifier for the instantiated AnnotatorModel

Type Members

  1. type AnnotationContent = Seq[Row]
    Attributes
    protected
    Definition Classes
    AnnotatorModel
  2. type AnnotatorType = String
    Definition Classes
    HasOutputAnnotatorType

Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. final def ##(): Int
    Definition Classes
    AnyRef → Any
  3. final def $[T](param: Param[T]): T
    Attributes
    protected
    Definition Classes
    Params
  4. def $$[T](feature: StructFeature[T]): T
    Attributes
    protected
    Definition Classes
    HasFeatures
  5. def $$[K, V](feature: MapFeature[K, V]): Map[K, V]
    Attributes
    protected
    Definition Classes
    HasFeatures
  6. def $$[T](feature: SetFeature[T]): Set[T]
    Attributes
    protected
    Definition Classes
    HasFeatures
  7. def $$[T](feature: ArrayFeature[T]): Array[T]
    Attributes
    protected
    Definition Classes
    HasFeatures
  8. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  9. def _transform(dataset: Dataset[_], recursivePipeline: Option[PipelineModel]): DataFrame
    Attributes
    protected
    Definition Classes
    AnnotatorModel
  10. def afterAnnotate(dataset: DataFrame): DataFrame
    Attributes
    protected
    Definition Classes
    AnnotatorModel
  11. val allowPunctuationInBetween: BooleanParam
  12. final def annotate(annotations: Seq[Annotation]): Seq[Annotation]
    Definition Classes
    ContextualEntityRuler → HasSimpleAnnotate
  13. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  14. def beforeAnnotate(dataset: Dataset[_]): Dataset[_]
    Attributes
    protected
    Definition Classes
    AnnotatorModel
  15. val caseSensitive: BooleanParam

    Whether to use case sensitive when matching values.

    Whether to use case sensitive when matching values. Default is false

  16. final def checkSchema(schema: StructType, inputAnnotatorType: String): Boolean
    Attributes
    protected
    Definition Classes
    HasInputAnnotationCols
  17. def checkValidEnvironment(spark: Option[SparkSession], scopes: Seq[String]): Unit
    Definition Classes
    CheckLicense
  18. def checkValidScope(scope: String): Unit
    Definition Classes
    CheckLicense
  19. def checkValidScopeAndEnvironment(scope: String, spark: Option[SparkSession], checkLp: Boolean): Unit
    Definition Classes
    CheckLicense
  20. def checkValidScopesAndEnvironment(scopes: Seq[String], spark: Option[SparkSession], checkLp: Boolean): Unit
    Definition Classes
    CheckLicense
  21. final def clear(param: Param[_]): ContextualEntityRuler.this.type
    Definition Classes
    Params
  22. def clone(): AnyRef
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  23. def copy(extra: ParamMap): ContextualEntityRuler
    Definition Classes
    RawAnnotator → Model → Transformer → PipelineStage → Params
  24. def copyValues[T <: Params](to: T, extra: ParamMap): T
    Attributes
    protected
    Definition Classes
    Params
  25. final def defaultCopy[T <: Params](extra: ParamMap): T
    Attributes
    protected
    Definition Classes
    Params
  26. def dfAnnotate: UserDefinedFunction
    Definition Classes
    HasSimpleAnnotate
  27. val doExceptionHandling: BooleanParam

    If true, exceptions are handled.

    If true, exceptions are handled. If exception causing data is passed to the model, a error annotation is emitted which has the exception message. Processing continues with the next one. This comes with a performance penalty.

    Definition Classes
    HandleExceptionParams
  28. val dropEmptyChunks: BooleanParam

    Determines whether to drop chunks with empty content after the exclusion process, or if they should be retained unchanged.

    Determines whether to drop chunks with empty content after the exclusion process, or if they should be retained unchanged. For example, if a chunk like "September" is matched by a prefix pattern "September", and the mode is set to 'exclude', the chunk will be excluded. After exclusion, the decision is made whether to drop the chunk if its content is empty, or keep it unchanged.

  29. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  30. def equals(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  31. def explainParam(param: Param[_]): String
    Definition Classes
    Params
  32. def explainParams(): String
    Definition Classes
    Params
  33. def extraValidate(structType: StructType): Boolean
    Attributes
    protected
    Definition Classes
    RawAnnotator
  34. def extraValidateMsg: String
    Attributes
    protected
    Definition Classes
    RawAnnotator
  35. final def extractParamMap(): ParamMap
    Definition Classes
    Params
  36. final def extractParamMap(extra: ParamMap): ParamMap
    Definition Classes
    Params
  37. val features: ArrayBuffer[Feature[_, _, _]]
    Definition Classes
    HasFeatures
  38. def finalize(): Unit
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  39. def get[T](feature: StructFeature[T]): Option[T]
    Attributes
    protected
    Definition Classes
    HasFeatures
  40. def get[K, V](feature: MapFeature[K, V]): Option[Map[K, V]]
    Attributes
    protected
    Definition Classes
    HasFeatures
  41. def get[T](feature: SetFeature[T]): Option[Set[T]]
    Attributes
    protected
    Definition Classes
    HasFeatures
  42. def get[T](feature: ArrayFeature[T]): Option[Array[T]]
    Attributes
    protected
    Definition Classes
    HasFeatures
  43. final def get[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  44. def getAllowPunctuationInBetween: Boolean
  45. def getCaseSensitive: Boolean
  46. final def getClass(): Class[_]
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  47. final def getDefault[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  48. def getInputCols: Array[String]
    Definition Classes
    HasInputAnnotationCols
  49. def getLazyAnnotator: Boolean
    Definition Classes
    CanBeLazy
  50. def getMergeOverlapping: Boolean

    Whether to merge overlapping matched chunks.

    Whether to merge overlapping matched chunks. Defaults false

  51. final def getOrDefault[T](param: Param[T]): T
    Definition Classes
    Params
  52. final def getOutputCol: String
    Definition Classes
    HasOutputAnnotationCol
  53. def getParam(paramName: String): Param[Any]
    Definition Classes
    Params
  54. def getRules: Array[ContextualEntityRulerRules]

    Get ContextualEntityRulerRules param

  55. final def hasDefault[T](param: Param[T]): Boolean
    Definition Classes
    Params
  56. def hasParam(paramName: String): Boolean
    Definition Classes
    Params
  57. def hasParent: Boolean
    Definition Classes
    Model
  58. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  59. val inExceptionMode: Boolean
    Attributes
    protected
    Definition Classes
    HasSafeAnnotate
  60. def initializeLogIfNecessary(isInterpreter: Boolean, silent: Boolean): Boolean
    Attributes
    protected
    Definition Classes
    Logging
  61. def initializeLogIfNecessary(isInterpreter: Boolean): Unit
    Attributes
    protected
    Definition Classes
    Logging
  62. val inputAnnotatorTypes: Array[String]

    DOCUMENT, CHUNK, TOKEN

    DOCUMENT, CHUNK, TOKEN

    Definition Classes
    ContextualEntityRuler → HasInputAnnotationCols
  63. final val inputCols: StringArrayParam
    Attributes
    protected
    Definition Classes
    HasInputAnnotationCols
  64. final def isDefined(param: Param[_]): Boolean
    Definition Classes
    Params
  65. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  66. final def isSet(param: Param[_]): Boolean
    Definition Classes
    Params
  67. def isTraceEnabled(): Boolean
    Attributes
    protected
    Definition Classes
    Logging
  68. val lazyAnnotator: BooleanParam
    Definition Classes
    CanBeLazy
  69. def log: Logger
    Attributes
    protected
    Definition Classes
    Logging
  70. def logDebug(msg: ⇒ String, throwable: Throwable): Unit
    Attributes
    protected
    Definition Classes
    Logging
  71. def logDebug(msg: ⇒ String): Unit
    Attributes
    protected
    Definition Classes
    Logging
  72. def logError(msg: ⇒ String, throwable: Throwable): Unit
    Attributes
    protected
    Definition Classes
    Logging
  73. def logError(msg: ⇒ String): Unit
    Attributes
    protected
    Definition Classes
    Logging
  74. def logInfo(msg: ⇒ String, throwable: Throwable): Unit
    Attributes
    protected
    Definition Classes
    Logging
  75. def logInfo(msg: ⇒ String): Unit
    Attributes
    protected
    Definition Classes
    Logging
  76. def logName: String
    Attributes
    protected
    Definition Classes
    Logging
  77. def logTrace(msg: ⇒ String, throwable: Throwable): Unit
    Attributes
    protected
    Definition Classes
    Logging
  78. def logTrace(msg: ⇒ String): Unit
    Attributes
    protected
    Definition Classes
    Logging
  79. def logWarning(msg: ⇒ String, throwable: Throwable): Unit
    Attributes
    protected
    Definition Classes
    Logging
  80. def logWarning(msg: ⇒ String): Unit
    Attributes
    protected
    Definition Classes
    Logging
  81. val mergeOverlapping: BooleanParam

    whether to merge overlapping matched chunks.

    whether to merge overlapping matched chunks. Default false.

  82. def msgHelper(schema: StructType): String
    Attributes
    protected
    Definition Classes
    HasInputAnnotationCols
  83. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  84. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  85. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  86. def onWrite(path: String, spark: SparkSession): Unit
    Attributes
    protected
    Definition Classes
    ParamsAndFeaturesWritable
  87. val optionalInputAnnotatorTypes: Array[String]
    Definition Classes
    HasInputAnnotationCols
  88. val outputAnnotatorType: AnnotatorType

    CHUNK

    CHUNK

    Definition Classes
    ContextualEntityRuler → HasOutputAnnotatorType
  89. final val outputCol: Param[String]
    Attributes
    protected
    Definition Classes
    HasOutputAnnotationCol
  90. lazy val params: Array[Param[_]]
    Definition Classes
    Params
  91. var parent: Estimator[ContextualEntityRuler]
    Definition Classes
    Model
  92. val rules: StructFeature[Array[ContextualEntityRulerRules]]

    The rules parameter is used to set the rules.

    The rules parameter is used to set the rules. The rules is an array of ContextualEntityRulerRules.

  93. def safeAnnotate(annotations: Seq[Annotation]): Seq[Annotation]

    A protected method designed to safely annotate a sequence of Annotation objects by handling exceptions.

    A protected method designed to safely annotate a sequence of Annotation objects by handling exceptions.

    annotations

    A sequence of Annotation.

    returns

    A sequence of Annotation objects after processing, potentially containing error annotations.

    Attributes
    protected
    Definition Classes
    HasSafeAnnotate
  94. def save(path: String): Unit
    Definition Classes
    MLWritable
    Annotations
    @Since( "1.6.0" ) @throws( ... )
  95. def set[T](feature: StructFeature[T], value: T): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  96. def set[K, V](feature: MapFeature[K, V], value: Map[K, V]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  97. def set[T](feature: SetFeature[T], value: Set[T]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  98. def set[T](feature: ArrayFeature[T], value: Array[T]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  99. final def set(paramPair: ParamPair[_]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    Params
  100. final def set(param: String, value: Any): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    Params
  101. final def set[T](param: Param[T], value: T): ContextualEntityRuler.this.type
    Definition Classes
    Params
  102. def setAllowPunctuationInBetween(value: Boolean): ContextualEntityRuler.this.type
  103. def setCaseSensitive(value: Boolean): ContextualEntityRuler.this.type

    Whether to use case sensitive when matching values.

    Whether to use case sensitive when matching values. Default is false

  104. def setDefault[T](feature: StructFeature[T], value: () ⇒ T): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  105. def setDefault[K, V](feature: MapFeature[K, V], value: () ⇒ Map[K, V]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  106. def setDefault[T](feature: SetFeature[T], value: () ⇒ Set[T]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  107. def setDefault[T](feature: ArrayFeature[T], value: () ⇒ Array[T]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  108. final def setDefault(paramPairs: ParamPair[_]*): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    Params
  109. final def setDefault[T](param: Param[T], value: T): ContextualEntityRuler.this.type
    Attributes
    protected[org.apache.spark.ml]
    Definition Classes
    Params
  110. def setDoExceptionHandling(value: Boolean): ContextualEntityRuler.this.type

    If true, exceptions are handled.

    If true, exceptions are handled. If exception causing data is passed to the model, a error annotation is emitted which has the exception message. Processing continues with the next one. This comes with a performance penalty.

    Definition Classes
    HandleExceptionParams
  111. def setDropEmptyChunks(value: Boolean): ContextualEntityRuler.this.type
  112. final def setInputCols(value: String*): ContextualEntityRuler.this.type
    Definition Classes
    HasInputAnnotationCols
  113. def setInputCols(value: Array[String]): ContextualEntityRuler.this.type
    Definition Classes
    HasInputAnnotationCols
  114. def setLazyAnnotator(value: Boolean): ContextualEntityRuler.this.type
    Definition Classes
    CanBeLazy
  115. def setMergeOverlapping(v: Boolean): ContextualEntityRuler.this.type

    Whether to merge overlapping matched chunks.

    Whether to merge overlapping matched chunks. Defaults false

  116. final def setOutputCol(value: String): ContextualEntityRuler.this.type
    Definition Classes
    HasOutputAnnotationCol
  117. def setParent(parent: Estimator[ContextualEntityRuler]): ContextualEntityRuler
    Definition Classes
    Model
  118. def setRules(value: Array[ContextualEntityRulerRules]): ContextualEntityRuler.this.type

    Set the rules parameter.

    Set the rules parameter. The rules is an array of ContextualEntityRulerRules. Default: Array.empty

  119. def setRulesAsStr(value: String): ContextualEntityRuler.this.type
  120. final def synchronized[T0](arg0: ⇒ T0): T0
    Definition Classes
    AnyRef
  121. def toString(): String
    Definition Classes
    Identifiable → AnyRef → Any
  122. final def transform(dataset: Dataset[_]): DataFrame
    Definition Classes
    AnnotatorModel → Transformer
  123. def transform(dataset: Dataset[_], paramMap: ParamMap): DataFrame
    Definition Classes
    Transformer
    Annotations
    @Since( "2.0.0" )
  124. def transform(dataset: Dataset[_], firstParamPair: ParamPair[_], otherParamPairs: ParamPair[_]*): DataFrame
    Definition Classes
    Transformer
    Annotations
    @Since( "2.0.0" ) @varargs()
  125. final def transformSchema(schema: StructType): StructType
    Definition Classes
    RawAnnotator → PipelineStage
  126. def transformSchema(schema: StructType, logging: Boolean): StructType
    Attributes
    protected
    Definition Classes
    PipelineStage
    Annotations
    @DeveloperApi()
  127. val uid: String
    Definition Classes
    ContextualEntityRuler → Identifiable
  128. def validate(schema: StructType): Boolean
    Attributes
    protected
    Definition Classes
    RawAnnotator
  129. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  130. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  131. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  132. def wrapColumnMetadata(col: Column): Column
    Attributes
    protected
    Definition Classes
    RawAnnotator
  133. def write: MLWriter
    Definition Classes
    ParamsAndFeaturesWritable → DefaultParamsWritable → MLWritable

Inherited from CheckLicense

Inherited from HandleExceptionParams

Inherited from HasSimpleAnnotate[ContextualEntityRuler]

Inherited from AnnotatorModel[ContextualEntityRuler]

Inherited from CanBeLazy

Inherited from RawAnnotator[ContextualEntityRuler]

Inherited from HasOutputAnnotationCol

Inherited from HasInputAnnotationCols

Inherited from HasOutputAnnotatorType

Inherited from ParamsAndFeaturesWritable

Inherited from HasFeatures

Inherited from DefaultParamsWritable

Inherited from MLWritable

Inherited from Model[ContextualEntityRuler]

Inherited from Transformer

Inherited from PipelineStage

Inherited from Logging

Inherited from Params

Inherited from Serializable

Inherited from Serializable

Inherited from Identifiable

Inherited from AnyRef

Inherited from Any

Parameters

Annotator types

Required input and expected output annotator types

Members

Parameter setters

Parameter getters