Skip to main content

Spring AI RAG

Spring AI provides support for RAG.

There are some common types to use with RAG.

Document

Document represents documents in RAG. It has the following properties.

PropertyTypeDescription
idStringUnique document id
textStringDocument content
mediaMediaMedia content
metadataMap<String, Object>Document metadata
scoreDoubleNumeric score

Documents are created using its builder.

Create a Document
var doc = Document.builder().text("Content")
.metadata("field-1", "value-1")
.build();

Filter Expression

Filter expressions are used to filter documents with certain conditions. Spring AI defines common types of filter expressions. In the runtime, these expressions will be converted into vector-store specific expressions.

The following expression types are supported.

Expression type
AND, OR, EQ, NE, GT, GTE, LT, LTE, IN, NIN, NOT

Multiple expressions can be grouped to create complex expressions.

Filter expressions can be used the following ways.

  • Create record type Expression.
  • Use builder FilterExpressionBuilder.
  • Use simple filter expression syntax, then parsed using FilterExpressionTextParser.

Given some documents that describe technical articles, these documents have a metadata property topic representing the topic of an article. To select documents with the topic AI, we can use a filter expression.

The code below creates a filter expression using Expression.

Use Expression
new Expression(EQ, new Key("topic"), new Value("AI"));

The code below creates a filter expression using FilterExpressionBuilder.

Use FilterExpressionBuilder
var builder = new FilterExpressionBuilder();
builder.eq("topic", "AI");

The code below shows the expression string.

Use expression
topic == 'AI'