Rechercher

Artigo
· Out. 9 4min de leitura

Building a FHIR Vector Repository with InterSystems IRIS and Python through the IRIStool module

Introduction

In a previous article, I presented the IRIStool module, which seamlessly integrates the pandas Python library with the IRIS database. Now, I'm explaining how we can use IRIStool to leverage InterSystems IRIS as a foundation for intelligent, semantic search over healthcare data in FHIR format.

This article covers what I did to create the database for another of my projects, the FHIR Data Explorer. Both projects are candidates in the current InterSystems contest, so please vote for them if you find them useful.

You can find them at the Open Exchange:

In this article we'll cover:

  • Connecting to InterSystems IRIS database through Python
  • Creating a FHIR-ready database schema
  • Importing FHIR data with vector embeddings for semantic search

Prerequisites

Install IRIStool from the IRIStool and Data Manager GitHub page.

1. IRIS Connection Setup

Start by configuring your connection through environment variables in a .env file:

IRIS_HOST=localhost
IRIS_PORT=9092
IRIS_NAMESPACE=USER
IRIS_USER=_SYSTEM
IRIS_PASSWORD=SYS

Connect to IRIS using IRIStool's context manager:

from utils.iristool import IRIStool
import os
from dotenv import load_dotenv

load_dotenv()

with IRIStool(
    host=os.getenv('IRIS_HOST'),
    port=os.getenv('IRIS_PORT'),
    namespace=os.getenv('IRIS_NAMESPACE'),
    username=os.getenv('IRIS_USER'),
    password=os.getenv('IRIS_PASSWORD')
) as iris:
    # IRIStool manages the connection automatically
    pass

2. Creating the FHIR Schema

At first, create a table to store FHIR data, then while extracting data from FHIR bundles, create tables with vector search capabilities for each of the extracted FHIR resources (like Patient, Osservability, etc.). 

IRIStool simplifies table and index creation!

FHIR Repository Table

# Create main repository table for raw FHIR bundles
if not iris.table_exists("FHIRrepository", "SQLUser"):
    iris.create_table(
        table_name="FHIRrepository",
        columns={
            "patient_id": "VARCHAR(200)",
            "fhir_bundle": "CLOB"
        }
    )
    iris.quick_create_index(
        table_name="FHIRrepository",
        column_name="patient_id"
    )

Patient Table with Vector Support

# Create Patient table with vector column for semantic search
if not iris.table_exists("Patient", "SQLUser"):
    iris.create_table(
        table_name="Patient",
        columns={
            "patient_row_id": "INT AUTO_INCREMENT PRIMARY KEY",
            "patient_id": "VARCHAR(200)",
            "description": "CLOB",
            "description_vector": "VECTOR(FLOAT, 384)",
            "full_name": "VARCHAR(200)",
            "gender": "VARCHAR(30)",
            "age": "INTEGER",
            "birthdate": "TIMESTAMP"
        }
    )
    
    # Create standard indexes
    iris.quick_create_index(table_name="Patient", column_name="patient_id")
    iris.quick_create_index(table_name="Patient", column_name="age")
    
    # Create HNSW vector index for similarity search
    iris.create_hnsw_index(
        index_name="patient_vector_idx",
        table_name="Patient",
        column_name="description_vector",
        distance="Cosine"
    )

3. Importing FHIR Data with Vectors

Generate vector embeddings from FHIR patient descriptions and insert them into IRIS easily:

from sentence_transformers import SentenceTransformer

# Initialize transformer model
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')

# Example: Process patient data
patient_description = "45-year-old male with hypertension and type 2 diabetes"
patient_id = "patient-123"
# Generate vector embedding
vector = model.encode(patient_description, normalize_embeddings=True).tolist()

# Insert patient data with vector
iris.insert(
    table_name="Patient",
    patient_id=patient_id,
    description=patient_description,
    description_vector=str(vector),
    full_name="John Doe",
    gender="male",
    age=45,
    birthdate="1979-03-15"
)

4. Performing Semantic Search

Once your data is loaded, you can perform similarity searches:

# Search query
search_text = "patients with diabetes"
query_vector = model.encode(search_text, normalize_embeddings=True).tolist()

# define sql query
query = f"""
        SELECT TOP 5
            patient_id,
            full_name,
            description,
            VECTOR_COSINE(description_vector, TO_VECTOR(?)) as similarity
        FROM Patient
        ORDER BY similarity DESC
    """
# define query parameters
parameters = [str(query_vector)]

# Find similar patients using vector search
results = iris.query(query, parameters)

# print DataFrame data
if not results.empty:
    print(f"{results['full_name']}: {results['similarity']:.3f}")

Conclusion

  • IRIStool simplifies IRIS integration with intuitive Python methods for table and index creation
  • IRIS supports hybrid SQL + vector storage natively, enabling both traditional queries and semantic search
  • Vector embeddings enable intelligent search across FHIR healthcare data using natural language
  • HNSW indexes provide efficient similarity search at scale

This approach demonstrates how InterSystems IRIS can serve as a powerful foundation for building intelligent healthcare applications with semantic search capabilities over FHIR data.

Discussão (0)1
Entre ou crie uma conta para continuar
Anúncio
· Out. 9

Developer Community AI Is Taking a Break

Hi Community,

It seems our Developer Community AI has decided to take a coffee break ☕️ (probably after answering one too many tricky ObjectScript questions).

The importance of the coffee break

For now, it’s gone mysteriously silent and refuses to generate answers. We suspect it might be rethinking its life choices after reading one too many deeply philosophical ObjectScript questions.

We’ll let you know as soon as our digital colleague is back online, refreshed, and ready to assist you again. In the meantime, if you notice it suddenly waking up and replying again, please do let us know in the comments before it changes its mind.

Thanks for your patience, and remember: even AI needs a break sometimes. 😄

3 Comments
Discussão (3)4
Entre ou crie uma conta para continuar
Anúncio
· Out. 9

[Vídeo] Produções de Interoperabilidade Python

Olá Comunidade!

Estamos felizes em compartilhar um novo vídeo do nosso canal InterSystems Developers YouTube:

⏯  Produções de Interoperabilidade Python@ Ready 2025

Esta apresentação apresenta o Python Interoperability Productions no InterSystems IRIS, um framework que permite aos desenvolvedores criar produções de interoperabilidade completas inteiramente em Python, sem a necessidade de ObjectScript. A apresentação aborda os principais componentes de uma arquitetura de produção, incluindo passagem de mensagens, retornos de chamada e persistência. A sessão também demonstra como uma produção funciona de ponta a ponta: como as mensagens passam de serviço → processo → operação → de volta — e como os desenvolvedores podem personalizar a persistência, a serialização e os formatos de exibição da interface do usuário.

🗣 Apresentador: @Geet Kalra, Senior Systems Developer, InterSystems

Divirta-se assistindo e inscreva-se para mais vídeos! 👍

Discussão (0)1
Entre ou crie uma conta para continuar
Artigo
· Out. 9 3min de leitura

Criar uma conexão JDBC com o Cache

Quando precisamos integrar o Caché/IRIS com outros bancos de dados relacionais, uma pergunta comum surge: “Como configuro a conexão JDBC?”. A documentação oficial nem sempre fornece um guia passo a passo direto, o que pode ser frustrante, especialmente para iniciantes.

Neste artigo, vou guiá-lo por todo o processo de configuração de uma conexão JDBC com MySQL, desde o download do conector até o espelhamento de tabelas no Caché/IRIS.

Nota: Conexões JDBC no Caché/IRIS têm algumas limitações, especialmente em relação ao caching e ao uso de ResultSet. Em muitos casos, você pode precisar adaptar consultas manualmente e usar o objeto Gateway para lidar com cenários avançados.

1. Baixar o Conector JDBC do MySQL

O primeiro passo é baixar o driver JDBC oficial do MySQL.
Vá para: https://dev.mysql.com/downloads/connector/j/

2. Tornar o Conector Acessível

Após o download:

  1. Extraia o pacote
  2. Localize o arquivo.jar  (ex., mysql-connector-j-9.4.xx.jar).
  3. Copie o arquivo para uma pasta acessível ao Caché/IRIS, por exemplo:


3. Configurar a Conexão no Portal de Administração

Agora, vamos configurar a conexão dentro do Portal de Administração:

  1. Abra o Portal de Administração Caché/IRIS em seu navegador.
  2. Navegue até Gateway Sql Connections (Conexões SQL do Gateway).
  3. Clique em “Create New Connection” (Criar Nova Conexão).




Crie uma nova conexão e configure-a usando o exemplo fornecido:

,

4. Espelhar Tabelas Externas

  • Vá para a tela SQL no Menu
  • Clique em Assistant > Link Table (Assistente > Espelhar Tabela).
  • Selecione sua conexão (MySQL_Conn).
  • Escolha as tabelas que você deseja espelhar.
  • Confirme.

Configure as definições necessárias; esta parte é fácil e muito sugestiva. Uma vez feito isso, sua conexão JDBC estará pronta. Você poderá ver o banco de dados e as tabelas na própria tela SQL e poderá trazer os dados. Lembre-se que o MySQL usa crases (`) para formar o SELECT, e o Caché/IRIS usa aspas duplas ("), o que pode ser um problema ao realizar algumas consultas.
Após mapear as tabelas, você poderá visualizá-las na aba Tables (Tabelas) da tela SQL.

5. Considerações sobre a Sintaxe SQL

Uma questão comum:

  • O MySQL usa crases (`) para nomes de tabelas e colunas.
  • O Caché/IRIS usa aspas duplas (") para identificadores.
  • Ao selecionar as opções apropriadas na tela de configuração do Gateway (conforme mostrado na captura de tela), você pode resolver esse problema. No entanto, você também pode optar por deixar inalterado por qualquer motivo.

Isso pode causar problemas em consultas. Se necessário, ajuste manualmente a sintaxe ao escrever comandos SQL.

Conclusão

E é isso! Agora você tem uma conexão JDBC funcional entre Caché/IRIS e MySQL.

Com esta configuração, você pode:

  • Consultar dados do MySQL diretamente do Caché/IRIS.
  • Espelhar tabelas para o seu namespace para fácil integração.
  • Automatizar a troca de dados entre sistemas.

Embora o JDBC no Caché/IRIS tenha algumas limitações, esta configuração abrange a maioria das necessidades de integração de forma prática.

Discussão (0)1
Entre ou crie uma conta para continuar
Anúncio
· Out. 9

[Video] September Developer Meetup Recording - FHIR as an AI Platform

Hey Community,

The InterSystems team put on our monthly Developer Meetup with a triumphant return to CIC's Venture Café, the crowd including both new and familiar faces. Despite the shakeup in both location and topic, we had a full house of folks ready to listen, learn, and have discussions about health tech innovation!

The topic of our September meetup was FHIR, AI and Interoperability, and the work of a whole team of folks from InterSystems was presented in a talk on the subject. @Elijah Cotterrell and @Duc Lanwyn both presented on the topic of FHIR as an AI Platform: Starting with the history of standards up to and including FHIR, detouring into a technical discussion of FHIR and it's use in AI applications, and closing with a forward-facing look at its applications as a standard for synthetic data.
 

If you weren't able to attend, you can find the recording from the meetup available virtually at the link below:

⏯️ FHIR as an AI Platform: EHRs, Simulations, and Safety

Discussão (0)1
Entre ou crie uma conta para continuar