Skip to content

Commit eaff847

Browse files
simplified examples
1 parent d88b1ba commit eaff847

12 files changed

+140
-152
lines changed

examples/alias_migration.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
from fnmatch import fnmatch
4141
from typing import TYPE_CHECKING, Any, Dict, List, Optional
4242

43-
from elasticsearch_dsl import Document, Keyword, M, connections, mapped_field
43+
from elasticsearch_dsl import Document, Keyword, connections, mapped_field
4444

4545
ALIAS = "test-blog"
4646
PATTERN = ALIAS + "-*"
@@ -50,10 +50,10 @@ class BlogPost(Document):
5050
if TYPE_CHECKING:
5151
_id: int
5252

53-
title: M[str]
54-
tags: M[List[str]] = mapped_field(Keyword(multi=True))
55-
content: M[str]
56-
published: M[Optional[datetime]]
53+
title: str
54+
tags: List[str] = mapped_field(Keyword())
55+
content: str
56+
published: Optional[datetime] = mapped_field(default=None)
5757

5858
def is_published(self) -> bool:
5959
return bool(self.published and datetime.now() > self.published)
@@ -142,7 +142,6 @@ def main() -> None:
142142
title="Hello World!",
143143
tags=["testing", "dummy"],
144144
content=open(__file__).read(),
145-
published=None,
146145
)
147146
bp.save(refresh=True)
148147

examples/async/alias_migration.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
from fnmatch import fnmatch
4242
from typing import TYPE_CHECKING, Any, Dict, List, Optional
4343

44-
from elasticsearch_dsl import AsyncDocument, Keyword, M, async_connections, mapped_field
44+
from elasticsearch_dsl import AsyncDocument, Keyword, async_connections, mapped_field
4545

4646
ALIAS = "test-blog"
4747
PATTERN = ALIAS + "-*"
@@ -51,10 +51,10 @@ class BlogPost(AsyncDocument):
5151
if TYPE_CHECKING:
5252
_id: int
5353

54-
title: M[str]
55-
tags: M[List[str]] = mapped_field(Keyword(multi=True))
56-
content: M[str]
57-
published: M[Optional[datetime]]
54+
title: str
55+
tags: List[str] = mapped_field(Keyword())
56+
content: str
57+
published: Optional[datetime] = mapped_field(default=None)
5858

5959
def is_published(self) -> bool:
6060
return bool(self.published and datetime.now() > self.published)
@@ -143,7 +143,6 @@ async def main() -> None:
143143
title="Hello World!",
144144
tags=["testing", "dummy"],
145145
content=open(__file__).read(),
146-
published=None,
147146
)
148147
await bp.save(refresh=True)
149148

examples/async/completion.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
Completion,
3737
Keyword,
3838
Long,
39-
M,
4039
Text,
4140
analyzer,
4241
async_connections,
@@ -54,15 +53,15 @@
5453

5554

5655
class Person(AsyncDocument):
57-
name: M[str] = mapped_field(Text(fields={"keyword": Keyword()}))
58-
popularity: M[int] = mapped_field(Long())
56+
if TYPE_CHECKING:
57+
_id: Optional[int] = mapped_field(default=None)
58+
59+
name: str = mapped_field(Text(fields={"keyword": Keyword()}), default="")
60+
popularity: int = mapped_field(Long(), default=0)
5961

6062
# completion field with a custom analyzer
6163
suggest: Dict[str, Any] = mapped_field(Completion(analyzer=ascii_fold), init=False)
6264

63-
if TYPE_CHECKING:
64-
_id: Optional[int] = mapped_field(default=None)
65-
6665
def clean(self) -> None:
6766
"""
6867
Automatically construct the suggestion input and weight by taking all

examples/async/parent_child.py

Lines changed: 26 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@
5353
Join,
5454
Keyword,
5555
Long,
56-
M,
5756
Text,
5857
async_connections,
5958
mapped_field,
@@ -65,33 +64,41 @@ class User(InnerDoc):
6564
Class used to represent a denormalized user stored on other objects.
6665
"""
6766

68-
id: M[int] = mapped_field(Long(required=True))
69-
signed_up: M[Optional[datetime]] = mapped_field(Date())
70-
username: M[str] = mapped_field(Text(fields={"keyword": Keyword()}, required=True))
71-
email: M[Optional[str]] = mapped_field(Text(fields={"keyword": Keyword()}))
72-
location: M[Optional[str]] = mapped_field(Text(fields={"keyword": Keyword()}))
67+
id: int = mapped_field(Long())
68+
signed_up: Optional[datetime] = mapped_field(Date())
69+
username: str = mapped_field(Text(fields={"keyword": Keyword()}))
70+
email: Optional[str] = mapped_field(Text(fields={"keyword": Keyword()}))
71+
location: Optional[str] = mapped_field(Text(fields={"keyword": Keyword()}))
7372

7473

7574
class Comment(InnerDoc):
7675
"""
7776
Class wrapper for nested comment objects.
7877
"""
7978

80-
author: M[User]
81-
created: M[datetime]
82-
content: M[str]
79+
author: User
80+
created: datetime
81+
content: str
8382

8483

8584
class Post(AsyncDocument):
8685
"""
8786
Base class for Question and Answer containing the common fields.
8887
"""
8988

90-
author: M[User]
91-
created: M[Optional[datetime]]
92-
body: str
93-
question_answer: M[Any] = mapped_field(Join(relations={"question": "answer"}))
94-
comments: M[List[Comment]]
89+
author: User
90+
91+
if TYPE_CHECKING:
92+
_routing: str = mapped_field(default=None)
93+
_index: AsyncIndex = mapped_field(default=None)
94+
_id: Optional[int] = mapped_field(default=None)
95+
96+
created: Optional[datetime] = mapped_field(default=None)
97+
body: str = mapped_field(default="")
98+
comments: List[Comment] = mapped_field(default_factory=list)
99+
question_answer: Any = mapped_field(
100+
Join(relations={"question": "answer"}), default_factory=dict
101+
)
95102

96103
@classmethod
97104
def _matches(cls, hit: Dict[str, Any]) -> bool:
@@ -127,11 +134,10 @@ async def save(self, **kwargs: Any) -> None: # type: ignore[override]
127134

128135

129136
class Question(Post):
130-
if TYPE_CHECKING:
131-
_id: Optional[int]
132-
133-
tags: M[List[str]] # .tags will return empty list if not present
134-
title: M[str] = mapped_field(Text(fields={"keyword": Keyword()}))
137+
tags: List[str] = mapped_field(
138+
default_factory=list
139+
) # .tags will return empty list if not present
140+
title: str = mapped_field(Text(fields={"keyword": Keyword()}), default="")
135141

136142
@classmethod
137143
def _matches(cls, hit: Dict[str, Any]) -> bool:
@@ -162,7 +168,6 @@ async def add_answer(
162168
created=created,
163169
body=body,
164170
is_accepted=accepted,
165-
comments=[],
166171
)
167172
if commit:
168173
await answer.save()
@@ -192,11 +197,7 @@ async def save(self, **kwargs: Any) -> None: # type: ignore[override]
192197

193198

194199
class Answer(Post):
195-
if TYPE_CHECKING:
196-
_routing: str
197-
_index: AsyncIndex
198-
199-
is_accepted: M[bool]
200+
is_accepted: bool = mapped_field(default=False)
200201

201202
@classmethod
202203
def _matches(cls, hit: Dict[str, Any]) -> bool:
@@ -263,9 +264,6 @@ async def main() -> Answer:
263264
body="""
264265
I want to use elasticsearch, how do I do it from Python?
265266
""",
266-
created=datetime.now(),
267-
question_answer={},
268-
comments=[],
269267
)
270268
await question.save()
271269
answer = await question.add_answer(honza, "Just use `elasticsearch-py`!")

examples/async/percolate.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
AsyncDocument,
2424
AsyncSearch,
2525
Keyword,
26-
M,
2726
Percolator,
2827
Q,
2928
Query,
@@ -40,10 +39,8 @@ class BlogPost(AsyncDocument):
4039
if TYPE_CHECKING:
4140
_id: int
4241

43-
content: M[Optional[str]]
44-
tags: M[List[str]] = mapped_field(
45-
Keyword(multi=True, required=False), default_factory=list
46-
)
42+
content: Optional[str]
43+
tags: List[str] = mapped_field(Keyword(), default_factory=list)
4744

4845
class Index:
4946
name = "test-blogpost"
@@ -78,12 +75,12 @@ class PercolatorDoc(AsyncDocument):
7875
# relevant fields from BlogPost must be also present here for the queries
7976
# to be able to use them. Another option would be to use document
8077
# inheritance but save() would have to be reset to normal behavior.
81-
content: M[Optional[str]]
78+
content: Optional[str]
8279

8380
# the percolator query to be run against the doc
84-
query: M[Query] = mapped_field(Percolator())
81+
query: Query = mapped_field(Percolator())
8582
# list of tags to append to a document
86-
tags: M[List[str]] = mapped_field(Keyword(multi=True))
83+
tags: List[str] = mapped_field(Keyword(multi=True))
8784

8885
class Index:
8986
name = "test-percolator"

examples/async/sparse_vectors.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464
import json
6565
import os
6666
from datetime import datetime
67-
from typing import Dict, List, Optional
67+
from typing import Any, Dict, List, Optional
6868
from urllib.request import urlopen
6969

7070
import nltk # type: ignore
@@ -75,7 +75,6 @@
7575
AsyncSearch,
7676
InnerDoc,
7777
Keyword,
78-
M,
7978
Q,
8079
SparseVector,
8180
async_connections,
@@ -89,25 +88,25 @@
8988

9089

9190
class Passage(InnerDoc):
92-
content: M[Optional[str]]
93-
embedding: M[Dict[str, float]] = mapped_field(SparseVector(), init=False)
91+
content: Optional[str]
92+
embedding: Dict[str, float] = mapped_field(SparseVector(), init=False)
9493

9594

9695
class WorkplaceDoc(AsyncDocument):
9796
class Index:
9897
name = "workplace_documents_sparse"
9998
settings = {"default_pipeline": "elser_ingest_pipeline"}
10099

101-
name: M[Optional[str]]
102-
summary: M[Optional[str]]
103-
content: M[Optional[str]]
104-
created: M[Optional[str]]
105-
updated: M[Optional[datetime]]
106-
url: M[Optional[str]] = mapped_field(Keyword())
107-
category: M[Optional[str]] = mapped_field(Keyword())
108-
passages: M[List[Passage]] = mapped_field(default=[])
100+
name: str
101+
summary: str
102+
content: str
103+
created: datetime
104+
updated: Optional[datetime]
105+
url: str = mapped_field(Keyword())
106+
category: str = mapped_field(Keyword())
107+
passages: List[Passage] = mapped_field(default=[])
109108

110-
_model = None
109+
_model: Any = None
111110

112111
def clean(self) -> None:
113112
# split the content into sentences

examples/async/vectors.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
import json
4949
import os
5050
from datetime import datetime
51-
from typing import List, Optional, cast
51+
from typing import Any, List, Optional, cast
5252
from urllib.request import urlopen
5353

5454
import nltk # type: ignore
@@ -72,32 +72,34 @@
7272
# initialize sentence tokenizer
7373
nltk.download("punkt", quiet=True)
7474

75+
# this will be the embedding model
76+
embedding_model: Any = None
77+
7578

7679
class Passage(InnerDoc):
77-
content: M[str]
78-
embedding: M[List[float]] = mapped_field(DenseVector())
80+
content: str
81+
embedding: List[float] = mapped_field(DenseVector())
7982

8083

8184
class WorkplaceDoc(AsyncDocument):
8285
class Index:
8386
name = "workplace_documents"
8487

85-
name: M[str]
86-
summary: M[str]
87-
content: M[str]
88-
created: M[datetime]
89-
updated: M[Optional[datetime]]
90-
url: M[str] = mapped_field(Keyword(required=True))
91-
category: M[str] = mapped_field(Keyword(required=True))
88+
name: str
89+
summary: str
90+
content: str
91+
created: datetime
92+
updated: Optional[datetime]
93+
url: str = mapped_field(Keyword(required=True))
94+
category: str = mapped_field(Keyword(required=True))
9295
passages: M[List[Passage]] = mapped_field(default=[])
9396

94-
_model = None
95-
9697
@classmethod
9798
def get_embedding(cls, input: str) -> List[float]:
98-
if cls._model is None:
99-
cls._model = SentenceTransformer(MODEL_NAME)
100-
return cast(List[float], list(cls._model.encode(input)))
99+
global embedding_model
100+
if embedding_model is None:
101+
embedding_model = SentenceTransformer(MODEL_NAME)
102+
return cast(List[float], list(embedding_model.encode(input)))
101103

102104
def clean(self) -> None:
103105
# split the content into sentences

examples/completion.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
Document,
3636
Keyword,
3737
Long,
38-
M,
3938
Text,
4039
analyzer,
4140
connections,
@@ -53,15 +52,15 @@
5352

5453

5554
class Person(Document):
56-
name: M[str] = mapped_field(Text(fields={"keyword": Keyword()}))
57-
popularity: M[int] = mapped_field(Long())
55+
if TYPE_CHECKING:
56+
_id: Optional[int] = mapped_field(default=None)
57+
58+
name: str = mapped_field(Text(fields={"keyword": Keyword()}), default="")
59+
popularity: int = mapped_field(Long(), default=0)
5860

5961
# completion field with a custom analyzer
6062
suggest: Dict[str, Any] = mapped_field(Completion(analyzer=ascii_fold), init=False)
6163

62-
if TYPE_CHECKING:
63-
_id: Optional[int] = mapped_field(default=None)
64-
6564
def clean(self) -> None:
6665
"""
6766
Automatically construct the suggestion input and weight by taking all

0 commit comments

Comments
 (0)