
    dhڽ                        S SK r S SKrS SKJrJr  S SKJrJrJrJ	r	J
r
JrJrJrJrJr  S SKrS SKJr  S SKJr  S SKJr  S SKJr  S SKJrJr  \(       a  S S	KJr  \ R>                  " \ 5      r! " S
 S\5      r"\" SSSS9 " S S\"5      5       r#\" SSSS9 " S S\"5      5       r$\" SSSS9 " S S\"5      5       r%\" SSSS9 " S S\5      5       r&g)    N)ABCabstractmethod)
TYPE_CHECKINGAnyCallableDictIterableListLiteralOptionalTupleUnion)
deprecated)Document)
Embeddings)VectorStore)DistanceStrategymaximal_marginal_relevance)Elasticsearchc                       \ rS rSrSr\S\\\   S4   S\\	S4   S\
S\
S\	S	\	S
\\   S\\S4   S\4S j5       r\S\\
S4   S\	S\\S4   S\4S j5       rSSS	\	S\	SS4S jrS\4S jrSrg)BaseRetrievalStrategy"   z4Base class for `Elasticsearch` retrieval strategies.query_vectorNquerykfetch_kvector_query_field
text_fieldfilter
similarityreturnc                    g)a  
Executes when a search is performed on the store.

Args:
    query_vector: The query vector,
                  or None if not using vector-based query.
    query: The text query, or None if not using text-based query.
    k: The total number of results to retrieve.
    fetch_k: The number of results to fetch initially.
    vector_query_field: The field containing the vector
                        representations in the index.
    text_field: The field containing the text data in the index.
    filter: List of filter clauses to apply to the query.
    similarity: The similarity strategy to use, or None if not using one.

Returns:
    Dict: The Elasticsearch query body.
N 	selfr   r   r   r   r   r   r   r    s	            f/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/vectorstores/elasticsearch.pyr   BaseRetrievalStrategy.query%           dims_lengthc                     g)a  
Executes when the index is created.

Args:
    dims_length: Numeric length of the embedding vectors,
                or None if not using vector-based query.
    vector_query_field: The field containing the vector
                        representations in the index.
    similarity: The similarity strategy to use,
                or None if not using one.

Returns:
    Dict: The Elasticsearch settings and mappings for the strategy.
Nr#   r%   r*   r   r    s       r&   indexBaseRetrievalStrategy.indexE   r(   r)   clientr   c                     g)aM  
Executes before the index is created. Used for setting up
any required Elasticsearch resources like a pipeline.

Args:
    client: The Elasticsearch client.
    text_field: The field containing the text data in the index.
    vector_query_field: The field containing the vector
                        representations in the index.
Nr#   r%   r/   r   r   s       r&   before_index_setup(BaseRetrievalStrategy.before_index_setup[   r(   r)   c                     g)z
Returns whether or not the strategy requires inference
to be performed on the text before it is added to the index.

Returns:
    bool: Whether or not the strategy requires inference
    to be performed on the text before it is added to the index.
Tr#   r%   s    r&   require_inference'BaseRetrievalStrategy.require_inferencei   s     r)   r#   )__name__
__module____qualname____firstlineno____doc__r   r   r
   floatstrintdictr   r   r   r-   r2   boolr6   __static_attributes__r#   r)   r&   r   r   "   s   >DK-. S$Y
      T
 *D01 
 > 39%   *D01	
 
 *%36LO		4 	r)   r   z0.0.27z,Use class in langchain-elasticsearch packageT)alternativependingc                       \ rS rSrSr   SS\\   S\\   S\\\	\4      4S jjr
S\\\   S4   S	\\S4   S
\S\S\S\S\\	   S\\S4   S\4S jrS\\S4   S\S\\S4   S\4S jrSrg)ApproxRetrievalStrategyu   z:Approximate retrieval strategy using the `HNSW` algorithm.Nquery_model_idhybridrrfc                 (    Xl         X l        X0l        g NrH   rI   rJ   )r%   rH   rI   rJ   s       r&   __init__ ApproxRetrievalStrategy.__init__{   s     -
 r)   r   r   r   r   r   r   r   r    r!   c	                    UUUUS.n	U(       a  U R                   (       d  XS'   O8U(       a&  U R                   (       a  SU R                   US.0U	S'   O[        S5      eU R                  (       az  U	SSUS	U000/US
.0S.n
[        U R                  [
        5      (       a  SU R                  0U
S'   U
$ [        U R                  [        5      (       a  U R                  SL a  S0 0U
S'   U
$ SU	0$ )N)r   fieldr   num_candidatesr   text_embeddingmodel_id
model_textquery_vector_builderzZYou must provide an embedding function or a query_model_id to perform a similarity search.rA   matchr   mustr   )knnr   rJ   rankTr[   )rH   
ValueErrorrI   
isinstancerJ   r@   rA   )r%   r   r   r   r   r   r   r   r    r[   
query_bodys              r&   r   ApproxRetrievalStrategy.query   s    '%	
  3 3". t**  $ 3 3"'#+C&' B  ;; !($.(/1&*"! #)J$ $((D))&+TXX%6
6"  DHHd++D0@&+R[
6"3<r)   r*   c                     U[         R                  L a  SnOQU[         R                  L a  SnO;U[         R                  L a  SnO%U[         R                  L a  SnO[        SU S35      eSSUS	US
US.000$ )/Create the mapping for the Elasticsearch index.cosinel2_normdot_productmax_inner_productSimilarity  not supported.mappings
propertiesdense_vectorT)typedimsr-   r    )r   COSINEEUCLIDEAN_DISTANCEDOT_PRODUCTMAX_INNER_PRODUCTr]   )r%   r*   r   r    similarityAlgos        r&   r-   ApproxRetrievalStrategy.index   s     )000%N+>>>&N+777*N+===0N{:,oFGG & . +!%&4	)	
 	
r)   )rI   rH   rJ   NFT)r8   r9   r:   r;   r<   r   r>   rA   r   r@   rN   r
   r=   r?   r   r   r   r-   rB   r#   r)   r&   rF   rF   u   s    E )-!&+/	   eD$J'(	D DK-.D  S$YD  	D 
 D   D  D  T
D  *D01D  
D L
39%
  
 *D01	

 

r)   rF   c                       \ rS rSrSrS\\\   S4   S\\S4   S\	S\	S\S	\S
\\\
   S4   S\\S4   S\4S jrS\\	S4   S\S\\S4   S\4S jrSrg)ExactRetrievalStrategy   z8Exact retrieval strategy using the `script_score` query.r   Nr   r   r   r   r   r   r    r!   c	                     U[         R                  L a  SU S3n	OCU[         R                  L a  SU S3n	O)U[         R                  L a  SU S3n	O[	        SU S35      eS	0 0n
U(       a  S
SU00n
SSU
U	SU0S.S.00$ )Nz'cosineSimilarity(params.query_vector, 'z') + 1.0z&1 / (1 + l2norm(params.query_vector, 'z'))z=
            double value = dotProduct(params.query_vector, 'z?');
            return sigmoid(1, Math.E, -value);
            rg   rh   	match_allrA   r   r   script_scorer   )sourceparams)r   script)r   rn   ro   rp   r]   )r%   r   r   r   r   r   r   r   r    rr   	queryBools              r&   r   ExactRetrievalStrategy.query   s     )0009:L9MXV  +>>>89K8LCP  +777"==O<P QN
 {:,oFGG&+	(F!34I &"0#1<"@!

 
	
r)   r*   c                     SSUSUSS.000$ )rb   ri   rj   rk   F)rl   rm   r-   r#   r,   s       r&   r-   ExactRetrievalStrategy.index!  s/     & . +!&)

 
	
r)   r#   )r8   r9   r:   r;   r<   r   r
   r=   r>   r?   r@   r   r   r   r-   rB   r#   r)   r&   rv   rv      s     C)
DK-.)
 S$Y)
 	)

 )
  )
 )
 d4j$&')
 *D01)
 
)
V
39%
  
 *D01	

 

r)   rv   c                       \ rS rSrSrSS\\   4S jjrS\\	\
   S4   S\\S4   S\S	\S
\S\S\	\   S\\S4   S\4S jrS\4S jrSSS\S
\SS4S jrS\\S4   S
\S\\S4   S\4S jrS\4S jrSrg)SparseRetrievalStrategyi6  z?Sparse retrieval strategy using the `text_expansion` processor.NrU   c                 $    U=(       d    SU l         g )Nz.elser_model_1rU   )r%   rU   s     r&   rN    SparseRetrievalStrategy.__init__<  s     4$4r)   r   r   r   r   r   r   r   r    r!   c	                 >    SSSU S3U R                   US.00/US.00$ )Nr   rA   text_expansionz.tokensrT   rY   r   r$   s	            r&   r   SparseRetrievalStrategy.query?  sR      -#5"6g >0427A"/	 %
 	
r)   c                      U R                    S3$ )N_sparse_embeddingr   r5   s    r&   _get_pipeline_name*SparseRetrievalStrategy._get_pipeline_name\  s    -- 122r)   r/   r   c                     U R                   (       aB  UR                  R                  U R                  5       SSU R                   UUS0SSS00S.0/S9  g g )	Nz,Embedding pipeline for langchain vectorstore	inferencer   r   results_fieldtokens)rU   target_field	field_mapinference_config)iddescription
processors)rU   ingestput_pipeliner   r1   s       r&   r2   *SparseRetrievalStrategy.before_index_setup_  sk     ==MM&&**,J $(,,>*4l)C 0?H2M1	&	 '  r)   r*   c                 @    SUSSSS00000SU R                  5       0S.$ )Nrj   r   rl   rank_featuresdefault_pipeline)ri   settings)r   r,   s       r&   r-   SparseRetrievalStrategy.indexu  sE     &$x&/1J&K) ,T-D-D-FG	
 		
r)   c                     g)NFr#   r5   s    r&   r6   )SparseRetrievalStrategy.require_inference  s    r)   r   rL   )r8   r9   r:   r;   r<   r   r>   rN   r   r
   r=   r?   r@   r   r   r   r   r2   r-   rA   r6   rB   r#   r)   r&   r   r   6  s    J5# 5
DK-.
 S$Y
 	

 
  
 
 T

 *D01
 

:3C 3%36LO	,
39%
  
 *D01	

 

"4 r)   r   c                      \ rS rSrSrSSSSSSSSSS\" 5       SS.S\S\\   S	\S
   S\\   S\\   S\\   S\\   S\\   S\S\S\\	\
R                  \
R                  \
R                  \
R                  4      S\S\\\\4      4S jjr\S\4S j5       r\SSSSSSS.S\\   S\\   S\\   S\\   S\\   S\\\\4      SS
4S jj5       r\S\\   4S j5       r   SMS\S \S!\S"\\\      S#\S\\   4S$ jjr    SNS\S \S!\S%\S&\\\      S#\S\\   4S' jjr\S(\S\4S) j5       rS\ \/\4   4S* jr! SOS\S \S"\\\      S#\S\\"\\4      4
S+ jjr#  SOS\\   S \S"\\\      S#\S\\"\\4      4
S, jjr$        SPS\\   S \S-\%\\   S4   S!\S&\\\      S"\\\      S.\\ \\%\S4   /\4      S/\\ \/\4      S#\S\\"\\4      4S0 jjr&  SQS1\\\      S2\\'   S#\S\\'   4S3 jjr( SRS\S4\\   SS4S5 jjr)     SSS6\*\   S7\\\\         S8\\\\\4         S1\\\      S2\'S9\'S:\\   S#\S\\   4S; jjr+     SSS6\*\   S8\\\\\4         S1\\\      S2\'S9\'S:\\   S#\S\\   4S< jjr,     SSS=\*\"\\\   4      S8\\\      S1\\\      S2\'S9\'S:\\   S#\S\\   4S> jjr-\.   STS6\\   S\\   S8\\\\\4         S:\\   S#\SS 4S? jj5       r/\ SRS\\   S#\SS 4S@ jj5       r0\.  SUSA\\   S\\   S:\\   S#\SS 4
SB jj5       r1\SVSC j5       r2\   SWSD\\   SE\\'   SF\\%\\'4      SSG4SH jj5       r\ SRSI\\   SSJ4SK jj5       r3SLr4g)XElasticsearchStorei  a;  `Elasticsearch` vector store.

Example:
    .. code-block:: python

        from langchain_community.vectorstores import ElasticsearchStore
        from langchain_community.embeddings.openai import OpenAIEmbeddings

        vectorstore = ElasticsearchStore(
            embedding=OpenAIEmbeddings(),
            index_name="langchain-demo",
            es_url="http://localhost:9200"
        )

Args:
    index_name: Name of the Elasticsearch index to create.
    es_url: URL of the Elasticsearch instance to connect to.
    cloud_id: Cloud ID of the Elasticsearch instance to connect to.
    es_user: Username to use when connecting to Elasticsearch.
    es_password: Password to use when connecting to Elasticsearch.
    es_api_key: API key to use when connecting to Elasticsearch.
    es_connection: Optional pre-existing Elasticsearch connection.
    vector_query_field: Optional. Name of the field to store
                        the embedding vectors in.
    query_field: Optional. Name of the field to store the texts in.
    strategy: Optional. Retrieval strategy to use when searching the index.
             Defaults to ApproxRetrievalStrategy. Can be one of
             ExactRetrievalStrategy, ApproxRetrievalStrategy,
             or SparseRetrievalStrategy.
    distance_strategy: Optional. Distance strategy to use when
                        searching the index.
                        Defaults to COSINE. Can be one of COSINE,
                        EUCLIDEAN_DISTANCE, MAX_INNER_PRODUCT or DOT_PRODUCT.

If you want to use a cloud hosted Elasticsearch instance, you can pass in the
cloud_id argument instead of the es_url argument.

Example:
    .. code-block:: python

        from langchain_community.vectorstores import ElasticsearchStore
        from langchain_community.embeddings.openai import OpenAIEmbeddings

        vectorstore = ElasticsearchStore(
            embedding=OpenAIEmbeddings(),
            index_name="langchain-demo",
            es_cloud_id="<cloud_id>"
            es_user="elastic",
            es_password="<password>"
        )

You can also connect to an existing Elasticsearch instance by passing in a
pre-existing Elasticsearch connection via the es_connection argument.

Example:
    .. code-block:: python

        from langchain_community.vectorstores import ElasticsearchStore
        from langchain_community.embeddings.openai import OpenAIEmbeddings

        from elasticsearch import Elasticsearch

        es_connection = Elasticsearch("http://localhost:9200")

        vectorstore = ElasticsearchStore(
            embedding=OpenAIEmbeddings(),
            index_name="langchain-demo",
            es_connection=es_connection
        )

ElasticsearchStore by default uses the ApproxRetrievalStrategy, which uses the
HNSW algorithm to perform approximate nearest neighbor search. This is the
fastest and most memory efficient algorithm.

If you want to use the Brute force / Exact strategy for searching vectors, you
can pass in the ExactRetrievalStrategy to the ElasticsearchStore constructor.

Example:
    .. code-block:: python

        from langchain_community.vectorstores import ElasticsearchStore
        from langchain_community.embeddings.openai import OpenAIEmbeddings

        vectorstore = ElasticsearchStore(
            embedding=OpenAIEmbeddings(),
            index_name="langchain-demo",
            es_url="http://localhost:9200",
            strategy=ElasticsearchStore.ExactRetrievalStrategy()
        )

Both strategies require that you know the similarity metric you want to use
when creating the index. The default is cosine similarity, but you can also
use dot product or euclidean distance.

Example:
    .. code-block:: python

        from langchain_community.vectorstores import ElasticsearchStore
        from langchain_community.embeddings.openai import OpenAIEmbeddings
        from langchain_community.vectorstores.utils import DistanceStrategy

        vectorstore = ElasticsearchStore(
            "langchain-demo",
            embedding=OpenAIEmbeddings(),
            es_url="http://localhost:9200",
            distance_strategy="DOT_PRODUCT"
        )

Nvectortext)	embeddinges_connectiones_urles_cloud_ides_user
es_api_keyes_passwordr   query_fielddistance_strategystrategy	es_params
index_namer   r   r   r   r   r   r   r   r   r   r   r   r   c          	      z   X l         Xl        Xl        Xl        Uc  [        R
                  O[        U   U l        Xl        UbK  [        UR                  5      nUR                  SU R                  5       05        UR                  US9U l        g Uc  Ub  [        R                  UUUUUUS9U l        g [!        S5      e)N
user-agent)headers)r   usernamepasswordcloud_idapi_keyr   z{Either provide a pre-existing Elasticsearch connection,                 or valid credentials for creating a new connection.)r   r   r   r   r   rn   r   r   r@   _headersupdateget_user_agentoptionsr/   r   connect_to_elasticsearchr]   )r%   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                  r&   rN   ElasticsearchStore.__init__  s    0 #$&"4 !( ##!"34 	
 !$=112GNNL$*=*=*?@A'///@DK;#:,EE $$"# F DK G r)   r!   c                      SSK Jn   SU  3$ )Nr   __version__zlangchain-py-vs/)langchain_communityr   r   s    r&   r   !ElasticsearchStore.get_user_agent2  s    3!+//r)   )r   r   r   r   r   r   r   r   r   r   c                     SS K nU (       a  U(       a  [        S5      e0 nU (       a  U /US'   OU(       a  XS'   O[        S5      eU(       a  X'S'   OU(       a  U(       a  X44US'   Ub  UR                  U5        UR                  " S0 UDS	S
[
        R                  5       00D6n UR                  5         U$ ! [         a    [        S5      ef = f! [         a  n	[        R                  SU	 35        U	eS n	A	ff = f)Nr   bCould not import elasticsearch python package. Please install it with `pip install elasticsearch`.z>Both es_url and cloud_id are defined. Please provide only one.hostsr   z4Please provide either elasticsearch_url or cloud_id.r   
basic_authr   r   z#Error connecting to Elasticsearch: r#   )elasticsearchImportErrorr]   r   r   r   r   info	Exceptionloggererror)
r   r   r   r   r   r   r   connection_params	es_clientes
             r&   r   +ElasticsearchStore.connect_to_elasticsearch8  s   	  hP  -/*0g&,4j)STT+2i((/7.Bl+ $$Y/!// 

!#5#D#D#FG
		NN
 M  	F 	D  	LL>qcBCG	s#   B7 %C 7C
C9C44C9c                     U R                   $ rL   )r   r5   s    r&   
embeddingsElasticsearchStore.embeddingsl  s    ~~r)   r   r   r   r   kwargsc                 d    U R                   " SXX4S.UD6nU VVs/ sH  u  pxUPM	     snn$ s  snnf )a  Return Elasticsearch documents most similar to query.

Args:
    query: Text to look up documents similar to.
    k: Number of Documents to return. Defaults to 4.
    fetch_k (int): Number of Documents to fetch to pass to knn num_candidates.
    filter: Array of Elasticsearch filter clauses to apply to the query.

Returns:
    List of Documents most similar to the query,
    in descending order of similarity.
)r   r   r   r   r#   )_search)	r%   r   r   r   r   r   resultsdoc_s	            r&   similarity_search$ElasticsearchStore.similarity_searchp  s@    * ,, 
g
@F
 #**''***s   ,lambda_multfieldsc                 >   U R                   c  [        S5      eSnUc  U R                  /nO.U R                  U;  a  UR                  U R                  5        OSnU R                   R	                  U5      nU R
                  " SXUS.UD6n	U	 V
Vs/ sH  u  pU
R                  U R                     PM      nn
n[        [        R                  " U5      XUS9nU Vs/ sH
  oU   S   PM     nnU(       a   U H  n
U
R                  U R                  	 M     U$ s  snn
f s  snf )a  Return docs selected using the maximal marginal relevance.

Maximal marginal relevance optimizes for similarity to query AND diversity
    among selected documents.

Args:
    query (str): Text to look up documents similar to.
    k (int): Number of Documents to return. Defaults to 4.
    fetch_k (int): Number of Documents to fetch to pass to MMR algorithm.
    lambda_mult (float): Number between 0 and 1 that determines the degree
        of diversity among the results with 0 corresponding
        to maximum diversity and 1 to minimum diversity.
        Defaults to 0.5.
    fields: Other fields to get from elasticsearch source. These fields
        will be added to the document metadata.

Returns:
    List[Document]: A list of Documents selected by maximal marginal relevance.
z5You must provide an embedding function to perform MMRTF)r   r   r   )r   r   r   r#   )
r   r]   r   appendembed_queryr   metadatar   nparray)r%   r   r   r   r   r   r   'remove_vector_query_field_from_metadataquery_embeddinggot_docsr   r   got_embeddingsselected_indicesiselected_docss                   r&   max_marginal_relevance_search0ElasticsearchStore.max_marginal_relevance_search  s*   8 >>!TUU26/>--.F$$F2MM$1126;3 ..44U; << 
(F
FL

 OWWhFC#,,t'>'>?hW 6HH_%~RS
 2BB1AA!Q1AB2$LL!8!89 %  X Cs   $DDscorec                     U $ rL   r#   )r   s    r&   _identity_fnElasticsearchStore._identity_fn  s    r)   c                     U R                   $ )aK  
The 'correct' relevance function
may differ depending on a few things, including:
- the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
- embedding dimensionality
- etc.

Vectorstores should define their own selection based method of relevance.
)r   r5   s    r&   _select_relevance_score_fn-ElasticsearchStore._select_relevance_score_fn  s        r)   c                     [        U R                  [        5      (       a&  U R                  R                  (       a  [	        S5      eU R
                  " SXUS.UD6$ )aL  Return Elasticsearch documents most similar to query, along with scores.

Args:
    query: Text to look up documents similar to.
    k: Number of Documents to return. Defaults to 4.
    filter: Array of Elasticsearch filter clauses to apply to the query.

Returns:
    List of Documents most similar to the query and score for each
1scores are currently not supported in hybrid mode)r   r   r   r#   r^   r   rF   rI   r]   r   )r%   r   r   r   r   s        r&   similarity_search_with_score/ElasticsearchStore.similarity_search_with_score  sG     dmm%<==$--BVBVPQQ||F%VFvFFr)   c                     [        U R                  [        5      (       a&  U R                  R                  (       a  [	        S5      eU R
                  " SXUS.UD6$ )aY  Return Elasticsearch documents most similar to query, along with scores.

Args:
    embedding: Embedding to look up documents similar to.
    k: Number of Documents to return. Defaults to 4.
    filter: Array of Elasticsearch filter clauses to apply to the query.

Returns:
    List of Documents most similar to the embedding and score for each
r   )r   r   r   r#   r   )r%   r   r   r   r   s        r&   1similarity_search_by_vector_with_relevance_scoresDElasticsearchStore.similarity_search_by_vector_with_relevance_scores  sG    " dmm%<==$--BVBVPQQ||QQ&QQr)   r   custom_querydoc_builderc	                   ^  Uc  / nSU;  a  UR                  S5        T R                  U;  a  UR                  T R                  5        T R                  (       a!  Ub  Uc  T R                  R                  U5      nT R                  R                  UUUUT R                  T R                  U=(       d    / T R                  S9n
[        R                  SU
 35        Ub   U" X5      n
[        R                  SU
 35        T R                  R                  " SST R                  0U
DUUS.D6nS[        S[        4U 4S	 jjnU=(       d    Un/ nUS
   S
    Hh  nU HC  nXS   ;   d  M  UST R                  4;  d  M!  SUS   ;  a  0 US   S'   US   U   US   S   U'   ME     UR                  U" U5      US   45        Mj     U$ )a  Return Elasticsearch documents most similar to query, along with scores.

Args:
    query: Text to look up documents similar to.
    k: Number of Documents to return. Defaults to 4.
    query_vector: Embedding to look up documents similar to.
    fetch_k: Number of candidates to fetch from each shard.
            Defaults to 50.
    fields: List of fields to return from Elasticsearch.
            Defaults to only returning the text field.
    filter: Array of Elasticsearch filter clauses to apply to the query.
    custom_query: Function to modify the Elasticsearch
                 query body before it is sent to Elasticsearch.

Returns:
    List of Documents most similar to the query and score for each
r   )r   r   r   r   r   r   r   r    zQuery body: z&Calling custom_query, Query body now: r-   )sizer{   hitr!   c                 ^   > [        U S   R                  TR                  S5      U S   S   S9$ )N_source r   )page_contentr   )r   getr   )r  r%   s    r&   default_doc_builder7ElasticsearchStore._search.<locals>.default_doc_builderC  s6     ^//0@0@"EY
3 r)   hitsr  _scorer#   )r   r   r   r   r   r   r   r   r   debugr/   searchr   r   r   )r%   r   r   r   r   r   r   r   r   r   r_   responser  docs_and_scoresr  rQ   s   `               r&   r   ElasticsearchStore._search  s   : >FV#MM*%6)MM$**+>>e/L4H>>55e<L]]((%#66''<R-- ) 	

 	|J<01#%j8JLLA*NO;;%% 
//

 	
	T 	h 	 "8%8F#F+C	N*u$$= 0 "Y757Iz28;Iu8MC	N:.u5   ""$M ,  r)   idsrefresh_indicesc                 h    SSK JnJn  / nUc  [	        S5      eU H"  nUR                  SU R                  US.5        M$     [        U5      S:  a6   U" U R                  XbSS	9  [        R                  S
[        U5       S35        g[        R                  S5        g! [         a    [        S5      ef = f! U au  n[        R                  SU 35        UR                  S   R                  S0 5      R                  S0 5      n	[        R                  SU	R                  S5       35        UeSnAff = f)zDelete documents from the Elasticsearch index.

Args:
    ids: List of ids of documents to delete.
    refresh_indices: Whether to refresh the index
                    after deleting documents. Defaults to True.
r   BulkIndexErrorbulkr   Nzids must be provided.delete)_op_type_index_idi  )refreshignore_statuszDeleted z texts from indexTzError deleting texts: r-   r   First error reason: reasonzNo texts to delete from indexF)elasticsearch.helpersr  r  r   r]   r   r   lenr/   r   r  r   errorsr  )
r%   r  r  r   r  r  bodyr  r   
firstErrors
             r&   r  ElasticsearchStore.delete^  s&   	B ;455CKKXQTUV  t9q=	T[[$sSxD	{2CDE LL899  	F 	( " 5aS9:XXa[__Wb9==grJ
3JNN84L3MNO	s$   B 4B6 B36D1<A0D,,D1r*   c                 >   U R                   R                  R                  US9(       a  [        R	                  SU S35        gUc*  U R
                  R                  5       (       a  [        S5      eU R
                  R                  U R                   U R                  U R                  S9  U R
                  R                  U R                  UU R                  S9n[        R	                  SU S	US
    35        U R                   R                  R                  " SSU0UD6  g)zCreate the Elasticsearch index if it doesn't already exist.

Args:
    index_name: Name of the Elasticsearch index to create.
    dims_length: Length of the embedding vectors.
)r-   zIndex z# already exists. Skipping creation.NzCannot create index without specifying dims_length when the index doesn't already exist. We infer dims_length from the first embedding. Check that you have provided an embedding function.)r/   r   r   )r   r*   r    zCreating index z with mappings ri   r-   r#   )r/   indicesexistsr   r  r   r6   r]   r2   r   r   r-   r   create)r%   r   r*   indexSettingss       r&   _create_index_if_not_exists.ElasticsearchStore._create_index_if_not_exists  s	    ;;%%J%7LL6*-PQR "t}}'F'F'H'H ?  MM,,{{++#'#:#: -  !MM//#'#:#:'11 0 M
 LL!*_]:=V<WX KK&&IZI=Ir)   textsr   	metadatascreate_index_if_not_existsbulk_kwargsc                     SSK Jn	Jn
  U=(       d    0 nU=(       d.    U Vs/ sH!  n[	        [
        R                  " 5       5      PM#     snn/ nU(       a2  U(       a  [        US   5      nOS nU R                  U R                  US9  [        U5       H]  u  pU(       a  X>   O0 nSSSU R                  U R                  USUS	XN   0nU(       a  X.   UU R                  '   UR                  U5        M_     [        U5      S:  aR   U
" U R                  U4S
US.UD6u  nn[        R!                  SU SU S35        [        R!                  SU S35        U$ [        R!                  S5        / $ ! [         a    [        S5      ef = fs  snf ! U	 au  n[        R#                  SU 35        UR$                  S   R'                  S0 5      R'                  S0 5      n[        R#                  SUR'                  S5       35        UeS nAff = f)Nr   r  r   )r   r*   r  r-   r  r   r  T)
stats_onlyr  zAdded z and failed to add z texts to indexzadded texts z	 to indexzError adding texts: r   r  r  zNo texts to add to index)r  r  r  r   r>   uuiduuid4r  r)  r   	enumerater   r   r   r/   r   r  r   r   r  )r%   r+  r   r,  r  r  r-  r.  r   r  r  r   requestsr*   r   r   r   requestsuccessfailedr   r"  s                         r&   __addElasticsearchStore.__add  s   	B "'R77Ac$**,'7%!*Q-0",,?? -  !'GA'0y|bH G$//  $HsvG 3==//0OOG$ ( x=1"&KK#  $+	#
 "# WI%8P |C5	:;
 LL34Is  	F 	 8V " 3A378XXa[__Wb9==grJ
3JNN84L3MNO	s*   E+ 'FAF	 +F	HA0G??Hc                     U R                   b%  U R                   R                  [        U5      5      nOSnU R                  UUUUUUUUS9$ )a  Run more texts through the embeddings and add to the vectorstore.

Args:
    texts: Iterable of strings to add to the vectorstore.
    metadatas: Optional list of metadatas associated with the texts.
    ids: Optional list of ids to associate with the texts.
    refresh_indices: Whether to refresh the Elasticsearch indices
                    after adding the texts.
    create_index_if_not_exists: Whether to create the Elasticsearch
                                index if it doesn't already exist.
    *bulk_kwargs: Additional arguments to pass to Elasticsearch bulk.
        - chunk_size: Optional. Number of texts to add to the
            index at a time. Defaults to 500.

Returns:
    List of ids from adding the texts into the vectorstore.
Nr,  r  r  r-  r.  r   )r   embed_documentslist_ElasticsearchStore__add)	r%   r+  r,  r  r  r-  r.  r   r   s	            r&   	add_textsElasticsearchStore.add_texts  s]    6 >>% 77UDJ Jzz+'A#  	
 		
r)   text_embeddingsc                 f    [        U6 u  pU R                  [        U5      [        U	5      UUUUUUS9$ )a  Add the given texts and embeddings to the vectorstore.

Args:
    text_embeddings: Iterable pairs of string and embedding to
        add to the vectorstore.
    metadatas: Optional list of metadatas associated with the texts.
    ids: Optional list of unique IDs.
    refresh_indices: Whether to refresh the Elasticsearch indices
                    after adding the texts.
    create_index_if_not_exists: Whether to create the Elasticsearch
                                index if it doesn't already exist.
    *bulk_kwargs: Additional arguments to pass to Elasticsearch bulk.
        - chunk_size: Optional. Number of texts to add to the
            index at a time. Defaults to 500.

Returns:
    List of ids from adding the texts into the vectorstore.
r;  )zipr>  r=  )
r%   rA  r,  r  r  r-  r.  r   r+  r   s
             r&   add_embeddings!ElasticsearchStore.add_embeddings(  sH    8  1zzK+'A#  	
 		
r)   c                 V    [         R                  " SSU0UD6nUR                  XUS9  U$ )a  Construct ElasticsearchStore wrapper from raw documents.

Example:
    .. code-block:: python

        from langchain_community.vectorstores import ElasticsearchStore
        from langchain_community.embeddings.openai import OpenAIEmbeddings

        db = ElasticsearchStore.from_texts(
            texts,
            // embeddings optional if using
            // a strategy that doesn't require inference
            embeddings,
            index_name="langchain-demo",
            es_url="http://localhost:9200"
        )

Args:
    texts: List of texts to add to the Elasticsearch index.
    embedding: Embedding function to use to embed the texts.
    metadatas: Optional list of metadatas associated with the texts.
    index_name: Name of the Elasticsearch index to create.
    es_url: URL of the Elasticsearch instance to connect to.
    cloud_id: Cloud ID of the Elasticsearch instance to connect to.
    es_user: Username to use when connecting to Elasticsearch.
    es_password: Password to use when connecting to Elasticsearch.
    es_api_key: API key to use when connecting to Elasticsearch.
    es_connection: Optional pre-existing Elasticsearch connection.
    vector_query_field: Optional. Name of the field to
                        store the embedding vectors in.
    query_field: Optional. Name of the field to store the texts in.
    distance_strategy: Optional. Name of the distance
                        strategy to use. Defaults to "COSINE".
                        can be one of "COSINE",
                        "EUCLIDEAN_DISTANCE", "DOT_PRODUCT",
                        "MAX_INNER_PRODUCT".
    bulk_kwargs: Optional. Additional arguments to pass to
                Elasticsearch bulk.
r   )r,  r.  r#   )r   _create_cls_from_kwargsr?  )clsr+  r   r,  r.  r   elasticsearchStores          r&   
from_textsElasticsearchStore.from_textsP  sH    b 0GG 

#)

 	$$K 	% 	
 "!r)   c                    UR                  S5      nUc  [        S5      eUR                  S5      nUR                  S5      nUR                  S5      nUR                  S5      nUR                  S5      nUR                  S5      nUR                  S	5      n	UR                  S
5      n
UR                  S5      nUR                  S[        R                  5       5      n0 nU	b  XS	'   U
b  XS
'   [        SUU UUUUUUUUS.
UD6$ )Nr   zPlease provide an index_name.r   r   r   r   r   r   r   r   r   r   )
r   r   r   r   r   r   r   r   r   r   r#   )r  r]   r   rF   )r   r   r   r   r   r   r   r   r   r   r   r   r   optional_argss                 r&   rG  *ElasticsearchStore._create_cls_from_kwargs  s    ZZ-
<==

?3jj/H%**Y'jj/ZZ-
#ZZ(<=jj/"JJ':;::j*<*T*T*VW)2D./"+6-(! 
!'##!/
 
 	
r)   	documentsc                 T    [         R                  " SSU0UD6nUR                  XS9  U$ )a  Construct ElasticsearchStore wrapper from documents.

Example:
    .. code-block:: python

        from langchain_community.vectorstores import ElasticsearchStore
        from langchain_community.embeddings.openai import OpenAIEmbeddings

        db = ElasticsearchStore.from_documents(
            texts,
            embeddings,
            index_name="langchain-demo",
            es_url="http://localhost:9200"
        )

Args:
    texts: List of texts to add to the Elasticsearch index.
    embedding: Embedding function to use to embed the texts.
              Do not provide if using a strategy
              that doesn't require inference.
    metadatas: Optional list of metadatas associated with the texts.
    index_name: Name of the Elasticsearch index to create.
    es_url: URL of the Elasticsearch instance to connect to.
    cloud_id: Cloud ID of the Elasticsearch instance to connect to.
    es_user: Username to use when connecting to Elasticsearch.
    es_password: Password to use when connecting to Elasticsearch.
    es_api_key: API key to use when connecting to Elasticsearch.
    es_connection: Optional pre-existing Elasticsearch connection.
    vector_query_field: Optional. Name of the field
                        to store the embedding vectors in.
    query_field: Optional. Name of the field to store the texts in.
    bulk_kwargs: Optional. Additional arguments to pass to
                Elasticsearch bulk.
r   )r.  r#   )r   rG  add_documents)rH  rO  r   r.  r   rI  s         r&   from_documents!ElasticsearchStore.from_documents  s?    V 0GG 

#)
 	(((L!!r)   c                      [        5       $ )zMUsed to perform brute force / exact
nearest neighbor search via script_score.)rv   r#   r)   r&   rv   )ElasticsearchStore.ExactRetrievalStrategy  s     &''r)   rH   rI   rJ   rF   c                     [        XUS9$ )ap  Used to perform approximate nearest neighbor search
using the HNSW algorithm.

At build index time, this strategy will create a
dense vector field in the index and store the
embedding vectors in the index.

At query time, the text will either be embedded using the
provided embedding function or the query_model_id
will be used to embed the text using the model
deployed to Elasticsearch.

if query_model_id is used, do not provide an embedding function.

Args:
    query_model_id: Optional. ID of the model to use to
                    embed the query text within the stack. Requires
                    embedding model to be deployed to Elasticsearch.
    hybrid: Optional. If True, will perform a hybrid search
            using both the knn query and a text query.
            Defaults to False.
    rrf: Optional. rrf is Reciprocal Rank Fusion.
         When `hybrid` is True,
            and `rrf` is True, then rrf: {}.
            and `rrf` is False, then rrf is omitted.
            and isinstance(rrf, dict) is True, then pass in the dict values.
         rrf could be passed for adjusting 'rank_constant' and 'window_size'.
rM   )rF   rM   s      r&   rF   *ElasticsearchStore.ApproxRetrievalStrategy  s    D ')c
 	
r)   rU   r   c                     [        U S9$ )az  Used to perform sparse vector search via text_expansion.
Used for when you want to use ELSER model to perform document search.

At build index time, this strategy will create a pipeline that
will embed the text using the ELSER model and store the
resulting tokens in the index.

At query time, the text will be embedded using the ELSER
model and the resulting tokens will be used to
perform a text_expansion query.

Args:
    model_id: Optional. Default is ".elser_model_1".
            ID of the model to use to embed the query text
            within the stack. Requires embedding model to be
            deployed to Elasticsearch.
r   )r   r   s    r&   SparseVectorRetrievalStrategy0ElasticsearchStore.SparseVectorRetrievalStrategy  s    * '99r)   )r/   r   r   r   r   r   r   )   2   N)r[     g      ?N)r[  N)Nr[  Nr\  NNNN)NTrL   )NNTTN)NNN)NN)r!   rv   rt   )5r8   r9   r:   r;   r<   rF   r>   r   r   r   r   rn   rp   ro   rq   r   r   r   rN   staticmethodr   r   propertyr   r?   r
   r@   r   r   r=   r   r   r   r   r   r   r   r   r   rA   r  r)  r	   r>  r?  rD  classmethodrJ  rG  rR  rv   rY  rB   r#   r)   r&   r   r     sQ   ld +/37 $%)!%$(%)"*! *A*C.2-44 J'	4
  04 4 c]4 #4 SM4 c]4  4 4 $ '' ,, 33 224
4* (+4, DcN+-4l 0C 0 0
  !%"&!%"&"&.211 3-1 #	1
 3-1 3-1 DcN+1 
1 1f HZ0   '+++ + 	+
 d$+ + 
h+:  &*;; ; 	;
 ; c#; ; 
h;z E e  !HeWe^,D !  FJGG G.6tDz.BGUXG	eHeO$	%G* '+	R;R R d$	R
 R 
eHeO$	%R0  $15&*'+KO<@Z}Z Z DK-.	Z
 Z c#Z d$Z xuS$Y/?(@$(FGHZ hvx'789Z Z 
eHeO$	%Z| $(*.+d3i + "$+ 	+
 
$+\ =A$J$J,4SM$J	$JT 59#' $+/&*F}F T$u+./F Dc3h01	F
 d3i F F %)F d^F F 
cFV 59#' $+/&*-
}-
 Dc3h01-
 d3i 	-

 -
 %)-
 d^-
 -
 
c-
d +/#' $+/&*&
!%T%[(8"9:&
 DJ'&
 d3i 	&

 &
 %)&
 d^&
 &
 
c&
P  +/48&*9"Cy9" J'9" Dc3h01	9"
 d^9" 9" 
9" 9"v *.'
J''
:='
	'
 '
R  +/&*	0">0" J'0" d^	0"
 0" 
0" 0"d ( (
 (,!&+/#
 #
#
 eD$J'(#
 
#	#
 #
J "&:3-:	": :r)   r   )'loggingr1  abcr   r   typingr   r   r   r   r	   r
   r   r   r   r   numpyr   langchain_core._apir   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   &langchain_community.vectorstores.utilsr   r   r   r   	getLoggerr8   r   r   rF   rv   r   r   r#   r)   r&   <module>rk     s     #    * - 0 3
 +			8	$PC Pf HRVu
3 u
u
p HRV@
2 @
@
F HRVN3 NNb HRV]: ]:]:r)   