To search for a portion of a word using django-elasticsearch-dsl-drf, you can use the wildcard search feature.
Here is an example of how to use wildcard search:
ELASTICSEARCH_DSL={
'default': {
'hosts': 'localhost:9200'
},
}
from elasticsearch_dsl import analyzer
from django_elasticsearch_dsl import DocType, Index, fields
from .models import MyModel
my_index = Index('my_index')
# Define custom analyzer for partial word search
partial_word_analyzer = analyzer(
'partial_word_analyzer',
tokenizer='standard',
filter=['lowercase', 'edge_ngram']
)
@my_index.doc_type
class MyModelIndex(DocType):
title = fields.TextField(
analyzer=partial_word_analyzer,
fields={
'raw': fields.keyword()
}
)
description = fields.TextField(
analyzer='english',
fields={
'raw': fields.keyword()
}
)
class Meta:
model = MyModel
fields = [
'title',
'description'
]
In this example, we define a custom analyzer that uses the edge_ngram filter to generate partial word searches. We apply this analyzer to the title field. We also define a raw field for each field, which will not be analyzed and allows exact matches.
from django.shortcuts import render
from django_elasticsearch_dsl_drf.views import (
BaseSearchView
)
from .documents import MyModelIndex
class MyModelSearchView(BaseSearchView):
document = MyModelIndex
fields = [
'title',
'description'
]
serializer_class = MyModelDocumentSerializer
*
) in your query parameter to search for partial words. For example, to search for all titles containing the word "elasti":http://localhost:8000/api/search/?q=title:elasti*
This will return all titles containing words that start with the letters "elasti", such as "Elasticsearch", "Elasticity", etc.
Note that using wildcards can be slow and inefficient, so it is recommended to use an edge_ngram filter for partial word searches as shown in the example.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-08-15 11:00:00 +0000
Seen: 21 times
Last updated: Aug 12 '22
How can a DateTime Zone be changed to another DateTime Zone?
How can we direct to a randomly selected entry from a list using Nginx?
How can I load a text file in gensim?
How to stop the for-loop when a specific condition is fulfilled?
How can CSS variables in Angular Material 15 be replaced?
How can you obtain several parameters using a single GET request?
How can double quotes be added to strings within an array?
"How can a Boolean variable be saved in SQFLite?"