I have a requirement to find the start and end position of a particular word in a text.
Suppose my text is "The patient date of birth is 12/11/2019", and I am searching for "date of birth" in the text. Upon search I need to get start and end offset of the search string in the search result. Is it possible using elasticsearch?
What I have tried so far,
Created index:
PUT /medicalrecord
{
"mappings": {
"properties": {
"Name": "text",
"Text": { "type": "text", "term_vector": "with_positions_offsets" }
}
}
}
Input text
POST /medicalrecord/_doc
{
"Name": "medicalrecord 1",
"Text" : "The patient date of birth is 12/11/2019"
}
Below API gives back the begin and end position of all the words present in the document
GET /medicalrecord/_termvectors/[id]
{
"fields" : ["Text"],
"offsets" : true,
"positions" : true,
"term_statistics" : true,
"field_statistics" : true
}
Result->
{
"_index" : "medicalrecord",
"_type" : "_doc",
"_id" : "r0NhCXYBD643sv6Ogz-n",
"_version" : 1,
"found" : true,
"took" : 0,
"term_vectors" : {
"Text" : {
"field_statistics" : {
"sum_doc_freq" : 9,
"doc_count" : 1,
"sum_ttf" : 9
},
"terms" : {
"11" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 7,
"start_offset" : 32,
"end_offset" : 34
}
]
},
"12" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 6,
"start_offset" : 29,
"end_offset" : 31
}
]
},
"2019" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 8,
"start_offset" : 35,
"end_offset" : 39
}
]
},
"birth" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 4,
"start_offset" : 20,
"end_offset" : 25
}
]
},
"date" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 2,
"start_offset" : 12,
"end_offset" : 16
}
]
},
"is" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 5,
"start_offset" : 26,
"end_offset" : 28
}
]
},
"of" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 3,
"start_offset" : 17,
"end_offset" : 19
}
]
},
"patient" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 1,
"start_offset" : 4,
"end_offset" : 11
}
]
},
"the" : {
"doc_freq" : 1,
"ttf" : 1,
"term_freq" : 1,
"tokens" : [
{
"position" : 0,
"start_offset" : 0,
"end_offset" : 3
}
]
}
}
}
}
}
Like the above operation, upon search of "date of birth", can I get the result as,
"date of birth" : {
"start_offset" : 12,
"end_offset" : 25
}
If we have multiple occurrences, add that too in the result.
Thanks!