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. val allowTokensInBetween: BooleanParam
  13. final def annotate(annotations: Seq[Annotation]): Seq[Annotation]
    Definition Classes
    ContextualEntityRuler → HasSimpleAnnotate
  14. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  15. def beforeAnnotate(dataset: Dataset[_]): Dataset[_]
    Attributes
    protected
    Definition Classes
    AnnotatorModel
  16. val caseSensitive: BooleanParam

    Whether to use case sensitive when matching values.

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

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

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

    Whether to merge overlapping matched chunks.

    Whether to merge overlapping matched chunks. Defaults false

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

    Get ContextualEntityRulerRules param

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

    DOCUMENT, CHUNK, TOKEN

    DOCUMENT, CHUNK, TOKEN

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

    whether to merge overlapping matched chunks.

    whether to merge overlapping matched chunks. Default false.

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

    CHUNK

    CHUNK

    Definition Classes
    ContextualEntityRuler → HasOutputAnnotatorType
  91. final val outputCol: Param[String]
    Attributes
    protected
    Definition Classes
    HasOutputAnnotationCol
  92. lazy val params: Array[Param[_]]
    Definition Classes
    Params
  93. var parent: Estimator[ContextualEntityRuler]
    Definition Classes
    Model
  94. 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.

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

    Whether to allow tokens in between the prefix and suffix patterns.

    Whether to allow tokens in between the prefix and suffix patterns. Default false. Example: For the phrase "diabetes mellitus with complications": Original Chunk: "diabetes mellitus" Suffix Pattern: "complications" Updated Chunk: "diabetes mellitus with complications"

  106. 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

  107. def setDefault[T](feature: StructFeature[T], value: () ⇒ T): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  108. def setDefault[K, V](feature: MapFeature[K, V], value: () ⇒ Map[K, V]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  109. def setDefault[T](feature: SetFeature[T], value: () ⇒ Set[T]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  110. def setDefault[T](feature: ArrayFeature[T], value: () ⇒ Array[T]): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    HasFeatures
  111. final def setDefault(paramPairs: ParamPair[_]*): ContextualEntityRuler.this.type
    Attributes
    protected
    Definition Classes
    Params
  112. final def setDefault[T](param: Param[T], value: T): ContextualEntityRuler.this.type
    Attributes
    protected[org.apache.spark.ml]
    Definition Classes
    Params
  113. 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
  114. def setDropEmptyChunks(value: Boolean): ContextualEntityRuler.this.type
  115. final def setInputCols(value: String*): ContextualEntityRuler.this.type
    Definition Classes
    HasInputAnnotationCols
  116. def setInputCols(value: Array[String]): ContextualEntityRuler.this.type
    Definition Classes
    HasInputAnnotationCols
  117. def setLazyAnnotator(value: Boolean): ContextualEntityRuler.this.type
    Definition Classes
    CanBeLazy
  118. def setMergeOverlapping(v: Boolean): ContextualEntityRuler.this.type

    Whether to merge overlapping matched chunks.

    Whether to merge overlapping matched chunks. Defaults false

  119. final def setOutputCol(value: String): ContextualEntityRuler.this.type
    Definition Classes
    HasOutputAnnotationCol
  120. def setParent(parent: Estimator[ContextualEntityRuler]): ContextualEntityRuler
    Definition Classes
    Model
  121. 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

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