7👍
If the method mentioned in the link you posted works (I haven’t tested it on JSONField), then you’re overriding the wrong method: The method the elasticsearch app uses to prep the field is prepare_FOO
where FOO
is the field name.
So you need to call your method prepare_web_results()
instead of prepare_content_json()
since your field is web_results
. Now your method prepare_content_json
is useless as it will never be called.
If your JSONField has a fixed structure, you should return an object field with the corresponding structure:
class WebTechDoc(Document):
web_results = fields.ObjectField(properties={
"url": fields.TextField(),
"version": fields.TextField(),
"server": fields.TextField()})
def prepare_web_results(self, instance):
results = instance.web_results
url = results.keys()[0]
return {
"url": url,
"version": results[url]["Version"],
"server": results[url]["Server"]
}
Or if you’re less concerned about where exactly the search result comes from, you could just map the dictionary to a string and put it in a TextField()
instead of an ObjectField()
: return f"{instance.web_results}"
0👍
class MyType(DocType):
content_json = fields.ObjectField()
def prepare_content_json(self, instance):
return instance.content_json
This solution is working fine. I tried it myself.
0👍
I was using mongodb for my django application, and it was not indexing the JSONField
fields. After reviewing Field
classes of django_elasticsearch_dsl.fields
I have implemented my own JSONField
. The following code is based on your example.
from django_elasticsearch_dsl import Document
from django_elasticsearch_dsl import fields
from django_elasticsearch_dsl.registries import registry
class JSONField(fields.DEDField):
_param_defs = {
"fields": {"type": "field", "hash": True},
"analyzer": {"type": "analyzer"},
"search_analyzer": {"type": "analyzer"},
"search_quote_analyzer": {"type": "analyzer"},
}
name = "text"
@registry.register_document
class WebTechDoc(Document):
web_results = JSONField()