<jupyter_start><jupyter_text><jupyter_code># !pip install -U jina
import numpy as np
from jina import DocumentArray, Executor, requests


class CharEmbed(Executor):  # a simple character embedding with mean-pooling
    offset = 32  # letter `a`
    dim = 127 - offset + 1  # last pos reserved for `UNK`
    char_embd = np.eye(dim) * 1  # one-hot embedding for all chars

    @requests
    def foo(self, docs: DocumentArray, **kwargs):
        for d in docs:
            r_emb = [ord(c) - self.offset if self.offset <= ord(c) <= 127 else (self.dim - 1) for c in d.text]
            d.embedding = self.char_embd[r_emb, :].mean(axis=0)  # average pooling
from jina import DocumentArray, Executor, requests


class Indexer(Executor):
    _docs = DocumentArray()  # for storing all documents in memory

    @requests(on='/index')
    def foo(self, docs: DocumentArray, **kwargs):
        self._docs.extend(docs)  # extend stored `docs`

    @requests(on='/search')
    def bar(self, docs: DocumentArray, **kwargs):
        docs.match(self._docs, metric='euclidean', limit=20)
from jina import Flow

f = (Flow(port_expose=12345, protocol='http', cors=True)
        .add(uses=CharEmbed, replicas=2)
        .add(uses=Indexer))  # build a Flow, with 2 shard CharEmbed, tho unnecessary
from jina import Document

data = ["Hello World", "Hello Universe", "World Hello!", "Universe Hello!"]

from jina.types.request import Response


def print_matches(resp: Response):  # the callback function invoked when task is done
    for idx, d in enumerate(resp.docs[0].matches[:3]):  # print top-3 matches
        print(f'[{idx}]{d.scores["euclidean"].value:2f}: "{d.text}"')

with f:
    f.post('/index', (Document(text=t.strip()) for t in data if t.strip()))  # index all lines of _this_ file
    # f.block()  # block for listening request
    f.post('/search', Document(text=input("Enter your query\n")), on_done=print_matches)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13395157135497165, 'fraction_numerical': 0.01287995878413189, 'mean_word_length': 3.725060827250608, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '419718', 'license': 'MIT', 'n_tokens_mistral': 664, 'n_tokens_neox': 617, 'n_words': 192, 'path': 'Jina_Simple_Neural_Search.ipynb', 'repo_name': 'akshatdalton/simple-text-search', 'size': '1941'}