Tablestore Demo
This guide shows you how to directly use our DocumentStore
abstraction backed by Tablestore. By putting nodes in the docstore, this allows you to define multiple indices over the same underlying docstore, instead of duplicating data across indices.
%pip install llama-index-storage-docstore-tablestore%pip install llama-index-storage-index-store-tablestore%pip install llama-index-vector-stores-tablestore
%pip install llama-index-llms-dashscope%pip install llama-index-embeddings-dashscope
%pip install llama-index%pip install matplotlib
import nest_asyncio
nest_asyncio.apply()
import loggingimport sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
from llama_index.core import SimpleDirectoryReader, StorageContextfrom llama_index.core import VectorStoreIndex, SimpleKeywordTableIndexfrom llama_index.core import SummaryIndexfrom llama_index.core.response.notebook_utils import display_responsefrom llama_index.core import Settings
Config Tablestore
Section titled âConfig TablestoreâNext, we use tablestoreâs docsstore to perform a demo.
import getpassimport os
os.environ["tablestore_end_point"] = getpass.getpass("tablestore end_point:")os.environ["tablestore_instance_name"] = getpass.getpass( "tablestore instance_name:")os.environ["tablestore_access_key_id"] = getpass.getpass( "tablestore access_key_id:")os.environ["tablestore_access_key_secret"] = getpass.getpass( "tablestore access_key_secret:")
Config DashScope LLM
Section titled âConfig DashScope LLMâNext, we use dashscopeâs llm to perform a demo.
import osimport getpass
os.environ["DASHSCOPE_API_KEY"] = getpass.getpass("DashScope api key:")
Download Data
Section titled âDownload Dataâ!mkdir -p 'data/paul_graham/'!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
Load Documents
Section titled âLoad Documentsâreader = SimpleDirectoryReader("./data/paul_graham/")documents = reader.load_data()
Parse into Nodes
Section titled âParse into Nodesâfrom llama_index.core.node_parser import SentenceSplitter
nodes = SentenceSplitter().get_nodes_from_documents(documents)
Init Store/Embedding/LLM/StorageContext
Section titled âInit Store/Embedding/LLM/StorageContextâfrom llama_index.storage.docstore.tablestore import TablestoreDocumentStorefrom llama_index.storage.index_store.tablestore import TablestoreIndexStorefrom llama_index.vector_stores.tablestore import TablestoreVectorStorefrom llama_index.embeddings.dashscope import ( DashScopeEmbedding, DashScopeTextEmbeddingModels, DashScopeTextEmbeddingType,)from llama_index.llms.dashscope import DashScope, DashScopeGenerationModels
embedder = DashScopeEmbedding( model_name=DashScopeTextEmbeddingModels.TEXT_EMBEDDING_V3, # default demiension is 1024 text_type=DashScopeTextEmbeddingType.TEXT_TYPE_DOCUMENT,)
dashscope_llm = DashScope( model_name=DashScopeGenerationModels.QWEN_MAX, api_key=os.environ["DASHSCOPE_API_KEY"],)Settings.llm = dashscope_llm
docstore = TablestoreDocumentStore.from_config( endpoint=os.getenv("tablestore_end_point"), instance_name=os.getenv("tablestore_instance_name"), access_key_id=os.getenv("tablestore_access_key_id"), access_key_secret=os.getenv("tablestore_access_key_secret"),)
index_store = TablestoreIndexStore.from_config( endpoint=os.getenv("tablestore_end_point"), instance_name=os.getenv("tablestore_instance_name"), access_key_id=os.getenv("tablestore_access_key_id"), access_key_secret=os.getenv("tablestore_access_key_secret"),)
vector_store = TablestoreVectorStore( endpoint=os.getenv("tablestore_end_point"), instance_name=os.getenv("tablestore_instance_name"), access_key_id=os.getenv("tablestore_access_key_id"), access_key_secret=os.getenv("tablestore_access_key_secret"), vector_dimension=1024, # embedder dimension is 1024)vector_store.create_table_if_not_exist()vector_store.create_search_index_if_not_exist()
storage_context = StorageContext.from_defaults( docstore=docstore, index_store=index_store, vector_store=vector_store)
Add to docStore
Section titled âAdd to docStoreâstorage_context.docstore.add_documents(nodes)
Define & Add Multiple Indexes
Section titled âDefine & Add Multiple IndexesâEach index uses the same underlying Node.
# https://gpt-index.readthedocs.io/en/latest/api_reference/indices/list.htmlsummary_index = SummaryIndex(nodes, storage_context=storage_context)
# https://gpt-index.readthedocs.io/en/latest/api_reference/indices/vector_store.htmlvector_index = VectorStoreIndex( nodes, insert_batch_size=20, embed_model=embedder, storage_context=storage_context,)
# https://gpt-index.readthedocs.io/en/latest/api_reference/indices/table.htmlkeyword_table_index = SimpleKeywordTableIndex( nodes=nodes, storage_context=storage_context, llm=dashscope_llm,)
# NOTE: the docstore still has the same nodeslen(storage_context.docstore.docs)
44
Test out saving and loading
Section titled âTest out saving and loadingâ# NOTE: docstore and index_store is persisted in Tablestore by default# NOTE: here only need to persist simple vector store to diskstorage_context.persist()
# note down index IDslist_id = summary_index.index_idvector_id = vector_index.index_idkeyword_id = keyword_table_index.index_idprint(list_id, vector_id, keyword_id)
c05fec2a-ac87-4761-beeb-0901f9e6530e d0b021ed-3427-46ad-927d-12d72752dbc4 2e9bfc3a-5e69-408a-9430-7b0c8baf3d77
from llama_index.core import load_index_from_storage
# re-create storage contextstorage_context = StorageContext.from_defaults( docstore=docstore, index_store=index_store, vector_store=vector_store)
summary_index = load_index_from_storage( storage_context=storage_context, index_id=list_id,)keyword_table_index = load_index_from_storage( llm=dashscope_llm, storage_context=storage_context, index_id=keyword_id,)# You need to add "vector_store=xxx" to StorageContext to load vector index from Tablestorevector_index = load_index_from_storage( insert_batch_size=20, embed_model=embedder, storage_context=storage_context, index_id=vector_id,)
Test out some Queries
Section titled âTest out some QueriesâSettings.llm = dashscope_llmSettings.chunk_size = 1024
query_engine = summary_index.as_query_engine()list_response = query_engine.query("What is a summary of this document?")
display_response(list_response)
query_engine = vector_index.as_query_engine()vector_response = query_engine.query("What did the author do growing up?")
display_response(vector_response)
Final Response:
Growing up, the author was involved in writing and programming outside of school. Initially, they wrote short stories, which they now consider to be not very good, as they lacked much plot and focused more on charactersâ emotions. In terms of programming, the author started with an IBM 1401 at their junior high school, where they attempted to write basic programs in Fortran using punch cards. Later, after getting a TRS-80 microcomputer, the author delved deeper into programming, creating simple games, a program to predict the flight height of model rockets, and even a word processor that their father used for writing.
query_engine = keyword_table_index.as_query_engine()keyword_response = query_engine.query( "What did the author do after his time at YC?")
display_response(keyword_response)
Final Response:
After his time at YC, the author decided to take up painting, dedicating himself to it to see how good he could become. He spent most of 2014 focused on this. However, by November, he lost interest and stopped. Following this, he returned to writing essays and even ventured into topics beyond startups. In March 2015, he also began working on Lisp again.