{
  "id": "vecsets",
  "title": "Vector set embeddings",
  "url": "https://redis.io/docs/latest/develop/clients/php/vecsets/",
  "summary": "Index and query embeddings with Redis vector sets",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-05-05T09:23:06-05:00",
  "page_type": "content",
  "content_hash": "e24be6011acb47451233813f3db96fbf6d2e6d92d52a9e53472f239ea8c4e621",
  "sections": [
    {
      "id": "initialize",
      "title": "Initialize",
      "role": "content",
      "text": "Install `Predis` and `TransformersPHP` with Composer:\n\n[code example]\n\nIn a new PHP file, import the required classes and function:\n\nFoundational: Import required libraries for vector sets, embeddings, and Redis operations\n\n**Difficulty:** Beginner\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]\n\n\n\nThe `pipeline()` function below creates an embedding generator for the\n[`all-MiniLM-L6-v2`](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2)\nmodel. This model generates vectors with 384 dimensions, regardless of the\nlength of the input text:\n\nFoundational: Initialize a TransformersPHP embedding pipeline to generate vectors from text\n\n**Difficulty:** Beginner\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]"
    },
    {
      "id": "create-the-data",
      "title": "Create the data",
      "role": "content",
      "text": "The example data is an array containing brief descriptions of famous people:\n\nFoundational: Define sample data with text descriptions and metadata for vector embedding and storage\n\n**Difficulty:** Beginner\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]"
    },
    {
      "id": "add-the-data-to-a-vector-set",
      "title": "Add the data to a vector set",
      "role": "content",
      "text": "The next step is to connect to Redis and add the data to a new vector set.\n\nThe code below iterates through the array, uses the embedding pipeline to\ngenerate a `float` vector from each description, and then adds the result to a\nvector set called `famousPeople` with [`vadd()`](https://redis.io/docs/latest/commands/vadd).\nIt then stores the `born` and `died` values as element attributes using\n[`vsetattr()`](https://redis.io/docs/latest/commands/vsetattr), so you can use the metadata\nlater during queries.\n\nFoundational: Add embedding vectors to a vector set and attach metadata attributes for later filtering\n\n**Difficulty:** Beginner\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]"
    },
    {
      "id": "query-the-vector-set",
      "title": "Query the vector set",
      "role": "content",
      "text": "You can now query the data in the set. The basic approach is to generate\nanother embedding vector from the query text and pass it to\n[`vsim()`](https://redis.io/docs/latest/commands/vsim), which returns elements ranked in\norder of similarity to that query vector.\n\nStart with a simple query for \"actors\":\n\nVector similarity search: Find semantically similar items in a vector set using VSIM\n\n**Difficulty:** Intermediate\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]\n\n\n\nThis returns the following list of elements:\n\n[code example]\n\nThe first two people in the list are the two actors, as expected, but the\nremaining results are less directly related. By default, the search attempts\nto rank all the elements in the set. You can use the `count` parameter of\n`vsim()` to limit the list to the most relevant few results:\n\nVector similarity search with limits: Restrict results to the top K most similar items using the count parameter\n\n**Difficulty:** Intermediate\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]\n\n\n\nThe reason for using text embeddings rather than simple text search is that\nthe embeddings capture semantic information. This allows a query to find\nelements with a similar meaning even if the text is different. For example, the\nword \"entertainer\" doesn't appear in any of the descriptions but if you use it\nas a query, the actors and musicians rank highly in the results:\n\nSemantic search: Use text embeddings to find related concepts even when exact keywords do not appear in the source text\n\n**Difficulty:** Intermediate\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]\n\n\n\nSimilarly, if you use \"science\" as a query, you get the scientists first,\nfollowed by the mathematicians:\n\n[code example]\n\nYou can also use\n[filter expressions](https://redis.io/docs/latest/develop/data-types/vector-sets/filtered-search)\nwith `vsim()` to restrict the search further. For example, repeat the\n\"science\" query, but this time limit the results to people who died before the\nyear 2000:\n\nFiltered vector search: Combine vector similarity with attribute filters to narrow results based on metadata conditions\n\n**Difficulty:** Advanced\n\n**Available in:** C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), PHP, Python\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]"
    },
    {
      "id": "more-information",
      "title": "More information",
      "role": "content",
      "text": "See the [vector sets](https://redis.io/docs/latest/develop/data-types/vector-sets)\ndocs for more information and code examples. See the\n[Redis for AI](https://redis.io/docs/latest/develop/ai) section for more details\nabout text embeddings and other AI techniques you can use with Redis.\n\nYou may also be interested in\n[vector search](https://redis.io/docs/latest/develop/clients/php/vecsearch).\nThis is a feature of\n[Redis Search](https://redis.io/docs/latest/develop/ai/search-and-query)\nthat lets you retrieve\n[JSON](https://redis.io/docs/latest/develop/data-types/json) and\n[hash](https://redis.io/docs/latest/develop/data-types/hashes) documents based on\nvector data stored in their fields."
    }
  ],
  "examples": [
    {
      "id": "initialize-ex0",
      "language": "bash",
      "code": "composer require predis/predis codewithkyrian/transformers",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex1",
      "language": "csharp",
      "code": "// Suppress experimental API warnings for VectorSet\n#pragma warning disable SER001\n\nusing StackExchange.Redis;\n\nusing Microsoft.ML;\nusing Microsoft.ML.Transforms.Text;",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex2",
      "language": "go",
      "code": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/knights-analytics/hugot\"\n\t\"github.com/redis/go-redis/v9\"\n)",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex3",
      "language": "java",
      "code": "// Lettuce client and Redis Search classes.\nimport io.lettuce.core.*;\nimport io.lettuce.core.api.StatefulRedisConnection;\nimport io.lettuce.core.api.async.RedisAsyncCommands;\n\n// Standard library classes for data manipulation and\n// asynchronous programming.\nimport java.util.*;\nimport java.util.concurrent.CompletableFuture;\n\n// DJL classes for model loading and inference.\nimport ai.djl.huggingface.translator.TextEmbeddingTranslatorFactory;\nimport ai.djl.inference.Predictor;\nimport ai.djl.repository.zoo.Criteria;\nimport ai.djl.training.util.ProgressBar;",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex4",
      "language": "java",
      "code": "// Lettuce client and Redis Search classes.\nimport io.lettuce.core.*;\nimport io.lettuce.core.api.StatefulRedisConnection;\nimport io.lettuce.core.api.reactive.RedisReactiveCommands;\n\n// Standard library classes for data manipulation and\n// reactive programming.\nimport java.util.*;\nimport reactor.core.publisher.Mono;\n\n// DJL classes for model loading and inference.\nimport ai.djl.huggingface.translator.TextEmbeddingTranslatorFactory;\nimport ai.djl.inference.Predictor;\nimport ai.djl.repository.zoo.Criteria;\nimport ai.djl.training.util.ProgressBar;",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex5",
      "language": "java",
      "code": "import redis.clients.jedis.RedisClient;\nimport redis.clients.jedis.params.VAddParams;\nimport redis.clients.jedis.params.VSimParams;\n\nimport java.util.*;\n\n// DJL classes for model loading and inference.\nimport ai.djl.huggingface.translator.TextEmbeddingTranslatorFactory;\nimport ai.djl.inference.Predictor;\nimport ai.djl.repository.zoo.Criteria;\nimport ai.djl.training.util.ProgressBar;",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex6",
      "language": "javascript",
      "code": "import * as transformers from '@xenova/transformers';\nimport { createClient } from 'redis';",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex7",
      "language": "php",
      "code": "<?php\n\nrequire 'vendor/autoload.php';\n\nuse function Codewithkyrian\\Transformers\\Pipelines\\pipeline;\n\nuse Predis\\Client as PredisClient;",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex8",
      "language": "python",
      "code": "from sentence_transformers import SentenceTransformer\n\nimport redis\nimport numpy as np",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex9",
      "language": "csharp",
      "code": "static PredictionEngine<TextData, TransformedTextData> GetPredictionEngine()\n{\n    // Create a new ML context, for ML.NET operations. It can be used for\n    // exception tracking and logging, as well as the source of randomness.\n    var mlContext = new MLContext();\n\n    // Create an empty list as the dataset\n    var emptySamples = new List<TextData>();\n\n    // Convert sample list to an empty IDataView.\n    var emptyDataView = mlContext.Data.LoadFromEnumerable(emptySamples);\n\n    // A pipeline for converting text into a 150-dimension embedding vector\n    var textPipeline = mlContext.Transforms.Text.NormalizeText(\"Text\")\n        .Append(mlContext.Transforms.Text.TokenizeIntoWords(\"Tokens\",\n            \"Text\"))\n        .Append(mlContext.Transforms.Text.ApplyWordEmbedding(\"Features\",\n            \"Tokens\", WordEmbeddingEstimator.PretrainedModelKind\n            .SentimentSpecificWordEmbedding));\n\n    // Fit to data.\n    var textTransformer = textPipeline.Fit(emptyDataView);\n\n    // Create the prediction engine to get the embedding vector from the input text/string.\n    var predictionEngine = mlContext.Model.CreatePredictionEngine<TextData,\n        TransformedTextData>(textTransformer);\n\n    return predictionEngine;\n}",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex10",
      "language": "go",
      "code": "// Create a new Hugot session\n\tsession, err := hugot.NewGoSession()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\terr := session.Destroy()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\t// Download the model.\n\tdownloadOptions := hugot.NewDownloadOptions()\n\tdownloadOptions.OnnxFilePath = \"onnx/model.onnx\"\n\tmodelPath, err := hugot.DownloadModel(\n\t\t\"sentence-transformers/all-MiniLM-L6-v2\",\n\t\t\"./models/\",\n\t\tdownloadOptions,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Create feature extraction pipeline configuration\n\tconfig := hugot.FeatureExtractionConfig{\n\t\tModelPath: modelPath,\n\t\tName:      \"embeddingPipeline\",\n\t}\n\n\t// Create the feature extraction pipeline\n\tembeddingPipeline, err := hugot.NewPipeline(session, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex11",
      "language": "java",
      "code": "Predictor<String, float[]> predictor = null;\n\n        try {\n            Criteria<String, float[]> criteria = Criteria.builder().setTypes(String.class, float[].class)\n                    .optModelUrls(\"djl://ai.djl.huggingface.pytorch/sentence-transformers/all-MiniLM-L6-v2\")\n                    .optEngine(\"PyTorch\").optTranslatorFactory(new TextEmbeddingTranslatorFactory())\n                    .optProgress(new ProgressBar()).build();\n\n            predictor = criteria.loadModel().newPredictor();\n        } catch (Exception e) {\n            // ...\n        }",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex12",
      "language": "java",
      "code": "Predictor<String, float[]> predictor = null;\n\n        try {\n            Criteria<String, float[]> criteria = Criteria.builder().setTypes(String.class, float[].class)\n                    .optModelUrls(\"djl://ai.djl.huggingface.pytorch/sentence-transformers/all-MiniLM-L6-v2\")\n                    .optEngine(\"PyTorch\").optTranslatorFactory(new TextEmbeddingTranslatorFactory())\n                    .optProgress(new ProgressBar()).build();\n\n            predictor = criteria.loadModel().newPredictor();\n        } catch (Exception e) {\n            // ...\n        }",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex13",
      "language": "java",
      "code": "Predictor<String, float[]> predictor = null;\n\n        try {\n            Criteria<String, float[]> criteria = Criteria.builder().setTypes(String.class, float[].class)\n                    .optModelUrls(\"djl://ai.djl.huggingface.pytorch/sentence-transformers/all-MiniLM-L6-v2\")\n                    .optEngine(\"PyTorch\").optTranslatorFactory(new TextEmbeddingTranslatorFactory())\n                    .optProgress(new ProgressBar()).build();\n\n            predictor = criteria.loadModel().newPredictor();\n        } catch (Exception e) {\n            // ...\n        }",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex14",
      "language": "javascript",
      "code": "const pipe = await transformers.pipeline(\n    'feature-extraction', 'Xenova/all-MiniLM-L6-v2'\n);\n\nconst pipeOptions = {\n    pooling: 'mean',\n    normalize: true,\n};",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex15",
      "language": "php",
      "code": "$extractor = pipeline('embeddings', 'Xenova/all-MiniLM-L6-v2');",
      "section_id": "initialize"
    },
    {
      "id": "initialize-ex16",
      "language": "python",
      "code": "model = SentenceTransformer(\"sentence-transformers/all-MiniLM-L6-v2\")",
      "section_id": "initialize"
    },
    {
      "id": "create-the-data-ex0",
      "language": "csharp",
      "code": "Dictionary<string, dynamic> peopleData = new Dictionary<string, dynamic>\n{\n    [\"Marie Curie\"] = new\n    {\n        born = 1867,\n        died = 1934,\n        description = @\"\n        Polish-French chemist and physicist. The only person ever to win\n        two Nobel prizes for two different sciences.\n        \"\n    },\n    [\"Linus Pauling\"] = new\n    {\n        born = 1901,\n        died = 1994,\n        description = @\"\n        American chemist and peace activist. One of only two people to win two\n        Nobel prizes in different fields (chemistry and peace).\n        \"\n    },\n    [\"Freddie Mercury\"] = new\n    {\n        born = 1946,\n        died = 1991,\n        description = @\"\n        British musician, best known as the lead singer of the rock band\n        Queen.\n        \"\n    },\n    [\"Marie Fredriksson\"] = new\n    {\n        born = 1958,\n        died = 2019,\n        description = @\"\n        Swedish multi-instrumentalist, mainly known as the lead singer and\n        keyboardist of the band Roxette.\n        \"\n    },\n    [\"Paul Erdos\"] = new\n    {\n        born = 1913,\n        died = 1996,\n        description = @\"\n        Hungarian mathematician, known for his eccentric personality almost\n        as much as his contributions to many different fields of mathematics.\n        \"\n    },\n    [\"Maryam Mirzakhani\"] = new\n    {\n        born = 1977,\n        died = 2017,\n        description = @\"\n        Iranian mathematician. The first woman ever to win the Fields medal\n        for her contributions to mathematics.\n        \"\n    },\n    [\"Masako Natsume\"] = new\n    {\n        born = 1957,\n        died = 1985,\n        description = @\"\n        Japanese actress. She was very famous in Japan but was primarily\n        known elsewhere in the world for her portrayal of Tripitaka in the\n        TV series Monkey.\n        \"\n    },\n    [\"Chaim Topol\"] = new\n    {\n        born = 1935,\n        died = 2023,\n        description = @\"\n        Israeli actor and singer, usually credited simply as 'Topol'. He was\n        best known for his many appearances as Tevye in the musical Fiddler\n        on the Roof.\n        \"\n    }\n};",
      "section_id": "create-the-data"
    },
    {
      "id": "create-the-data-ex1",
      "language": "go",
      "code": "type PersonData struct {\n\tBorn        int\n\tDied        int\n\tDescription string\n}\n\nvar peopleData = map[string]PersonData{\n\t\"Marie Curie\": {\n\t\tBorn: 1867, Died: 1934,\n\t\tDescription: `Polish-French chemist and physicist. The only person ever to win\n\t\ttwo Nobel prizes for two different sciences.\n\t\t`,\n\t},\n\t\"Linus Pauling\": {\n\t\tBorn: 1901, Died: 1994,\n\t\tDescription: `American chemist and peace activist. One of only two people to win two\n\t\tNobel prizes in different fields (chemistry and peace).\n\t\t`,\n\t},\n\t\"Freddie Mercury\": {\n\t\tBorn: 1946, Died: 1991,\n\t\tDescription: `British musician, best known as the lead singer of the rock band\n\t\tQueen.\n\t\t`,\n\t},\n\t\"Marie Fredriksson\": {\n\t\tBorn: 1958, Died: 2019,\n\t\tDescription: `Swedish multi-instrumentalist, mainly known as the lead singer and\n\t\tkeyboardist of the band Roxette.\n\t\t`,\n\t},\n\t\"Paul Erdos\": {\n\t\tBorn: 1913, Died: 1996,\n\t\tDescription: `Hungarian mathematician, known for his eccentric personality almost\n\t\tas much as his contributions to many different fields of mathematics.\n\t\t`,\n\t},\n\t\"Maryam Mirzakhani\": {\n\t\tBorn: 1977, Died: 2017,\n\t\tDescription: `Iranian mathematician. The first woman ever to win the Fields medal\n\t\tfor her contributions to mathematics.\n\t\t`,\n\t},\n\t\"Masako Natsume\": {\n\t\tBorn: 1957, Died: 1985,\n\t\tDescription: `Japanese actress. She was very famous in Japan but was primarily\n\t\tknown elsewhere in the world for her portrayal of Tripitaka in the\n\t\tTV series Monkey.\n\t\t`,\n\t},\n\t\"Chaim Topol\": {\n\t\tBorn: 1935, Died: 2023,\n\t\tDescription: `Israeli actor and singer, usually credited simply as 'Topol'. He was\n\t\tbest known for his many appearances as Tevye in the musical Fiddler\n\t\ton the Roof.\n\t\t`,\n\t},\n}",
      "section_id": "create-the-data"
    },
    {
      "id": "create-the-data-ex2",
      "language": "java",
      "code": "final class Person {\n            final String name;\n            final int born;\n            final int died;\n            final String description;\n            Person(String name, int born, int died, String description) {\n                this.name = name; this.born = born; this.died = died; this.description = description;\n            }\n        }\n\n        List<Person> people = Arrays.asList(\n            new Person(\n                \"Marie Curie\",\n                1867, 1934,\n                \"Polish-French chemist and physicist. The only person ever to win\" +\n                \" two Nobel prizes for two different sciences.\"\n            ),\n            new Person(\n                \"Linus Pauling\",\n                1901, 1994,\n                \"American chemist and peace activist. One of only two people to\" +\n                \" win two Nobel prizes in different fields (chemistry and peace).\"\n            ),\n            new Person(\n                \"Freddie Mercury\",\n                1946, 1991,\n                \"British musician, best known as the lead singer of the rock band Queen.\"\n            ),\n            new Person(\n                \"Marie Fredriksson\",\n                1958, 2019,\n                \"Swedish multi-instrumentalist, mainly known as the lead singer and\" +\n                \" keyboardist of the band Roxette.\"\n            ),\n            new Person(\n                \"Paul Erdos\",\n                1913, 1996,\n                \"Hungarian mathematician, known for his eccentric personality almost\" +\n                \" as much as his contributions to many different fields of mathematics.\"\n            ),\n            new Person(\n                \"Maryam Mirzakhani\",\n                1977, 2017,\n                \"Iranian mathematician. The first woman ever to win the Fields medal\" +\n                \" for her contributions to mathematics.\"\n            ),\n            new Person(\n                \"Masako Natsume\",\n                1957, 1985,\n                \"Japanese actress. She was very famous in Japan but was primarily\" +\n                \" known elsewhere in the world for her portrayal of Tripitaka in the\" +\n                \" TV series Monkey.\"\n            ),\n            new Person(\n                \"Chaim Topol\",\n                1935, 2023,\n                \"Israeli actor and singer, usually credited simply as 'Topol'. He was\" +\n                \" best known for his many appearances as Tevye in the musical Fiddler\" +\n                \" on the Roof.\"\n            )\n        );",
      "section_id": "create-the-data"
    },
    {
      "id": "create-the-data-ex3",
      "language": "java",
      "code": "final class Person {\n            final String name;\n            final int born;\n            final int died;\n            final String description;\n            Person(String name, int born, int died, String description) {\n                this.name = name; this.born = born; this.died = died; this.description = description;\n            }\n        }\n\n        List<Person> people = Arrays.asList(\n            new Person(\n                \"Marie Curie\",\n                1867, 1934,\n                \"Polish-French chemist and physicist. The only person ever to win\" +\n                \" two Nobel prizes for two different sciences.\"\n            ),\n            new Person(\n                \"Linus Pauling\",\n                1901, 1994,\n                \"American chemist and peace activist. One of only two people to\" +\n                \" win two Nobel prizes in different fields (chemistry and peace).\"\n            ),\n            new Person(\n                \"Freddie Mercury\",\n                1946, 1991,\n                \"British musician, best known as the lead singer of the rock band Queen.\"\n            ),\n            new Person(\n                \"Marie Fredriksson\",\n                1958, 2019,\n                \"Swedish multi-instrumentalist, mainly known as the lead singer and\" +\n                \" keyboardist of the band Roxette.\"\n            ),\n            new Person(\n                \"Paul Erdos\",\n                1913, 1996,\n                \"Hungarian mathematician, known for his eccentric personality almost\" +\n                \" as much as his contributions to many different fields of mathematics.\"\n            ),\n            new Person(\n                \"Maryam Mirzakhani\",\n                1977, 2017,\n                \"Iranian mathematician. The first woman ever to win the Fields medal\" +\n                \" for her contributions to mathematics.\"\n            ),\n            new Person(\n                \"Masako Natsume\",\n                1957, 1985,\n                \"Japanese actress. She was very famous in Japan but was primarily\" +\n                \" known elsewhere in the world for her portrayal of Tripitaka in the\" +\n                \" TV series Monkey.\"\n            ),\n            new Person(\n                \"Chaim Topol\",\n                1935, 2023,\n                \"Israeli actor and singer, usually credited simply as 'Topol'. He was\" +\n                \" best known for his many appearances as Tevye in the musical Fiddler\" +\n                \" on the Roof.\"\n            )\n        );",
      "section_id": "create-the-data"
    },
    {
      "id": "create-the-data-ex4",
      "language": "java",
      "code": "final class Person {\n            final String name;\n            final int born;\n            final int died;\n            final String description;\n            Person(String name, int born, int died, String description) {\n                this.name = name; this.born = born; this.died = died; this.description = description;\n            }\n        }\n\n        List<Person> people = Arrays.asList(\n            new Person(\n                \"Marie Curie\",\n                1867, 1934,\n                \"Polish-French chemist and physicist. The only person ever to win\" +\n                \" two Nobel prizes for two different sciences.\"\n            ),\n            new Person(\n                \"Linus Pauling\",\n                1901, 1994,\n                \"American chemist and peace activist. One of only two people to\" +\n                \" win two Nobel prizes in different fields (chemistry and peace).\"\n            ),\n            new Person(\n                \"Freddie Mercury\",\n                1946, 1991,\n                \"British musician, best known as the lead singer of the rock band Queen.\"\n            ),\n            new Person(\n                \"Marie Fredriksson\",\n                1958, 2019,\n                \"Swedish multi-instrumentalist, mainly known as the lead singer and\" +\n                \" keyboardist of the band Roxette.\"\n            ),\n            new Person(\n                \"Paul Erdos\",\n                1913, 1996,\n                \"Hungarian mathematician, known for his eccentric personality almost\" +\n                \" as much as his contributions to many different fields of mathematics.\"\n            ),\n            new Person(\n                \"Maryam Mirzakhani\",\n                1977, 2017,\n                \"Iranian mathematician. The first woman ever to win the Fields medal\" +\n                \" for her contributions to mathematics.\"\n            ),\n            new Person(\n                \"Masako Natsume\",\n                1957, 1985,\n                \"Japanese actress. She was very famous in Japan but was primarily\" +\n                \" known elsewhere in the world for her portrayal of Tripitaka in the\" +\n                \" TV series Monkey.\"\n            ),\n            new Person(\n                \"Chaim Topol\",\n                1935, 2023,\n                \"Israeli actor and singer, usually credited simply as 'Topol'. He was\" +\n                \" best known for his many appearances as Tevye in the musical Fiddler\" +\n                \" on the Roof.\"\n            )\n        );",
      "section_id": "create-the-data"
    },
    {
      "id": "create-the-data-ex5",
      "language": "javascript",
      "code": "const peopleData = {\n    \"Marie Curie\": {\n        \"born\": 1867, \"died\": 1934,\n        \"description\": `\n        Polish-French chemist and physicist. The only person ever to win\n        two Nobel prizes for two different sciences.\n        `\n    },\n    \"Linus Pauling\": {\n        \"born\": 1901, \"died\": 1994,\n        \"description\": `\n        American chemist and peace activist. One of only two people to win two\n        Nobel prizes in different fields (chemistry and peace).\n        `\n    },\n    \"Freddie Mercury\": {\n        \"born\": 1946, \"died\": 1991,\n        \"description\": `\n        British musician, best known as the lead singer of the rock band\n        Queen.\n        `\n    },\n    \"Marie Fredriksson\": {\n        \"born\": 1958, \"died\": 2019,\n        \"description\": `\n        Swedish multi-instrumentalist, mainly known as the lead singer and\n        keyboardist of the band Roxette.\n        `\n    },\n    \"Paul Erdos\": {\n        \"born\": 1913, \"died\": 1996,\n        \"description\": `\n        Hungarian mathematician, known for his eccentric personality almost\n        as much as his contributions to many different fields of mathematics.\n        `\n    },\n    \"Maryam Mirzakhani\": {\n        \"born\": 1977, \"died\": 2017,\n        \"description\": `\n        Iranian mathematician. The first woman ever to win the Fields medal\n        for her contributions to mathematics.\n        `\n    },\n    \"Masako Natsume\": {\n        \"born\": 1957, \"died\": 1985,\n        \"description\": `\n        Japanese actress. She was very famous in Japan but was primarily\n        known elsewhere in the world for her portrayal of Tripitaka in the\n        TV series Monkey.\n        `\n    },\n    \"Chaim Topol\": {\n        \"born\": 1935, \"died\": 2023,\n        \"description\": `\n        Israeli actor and singer, usually credited simply as 'Topol'. He was\n        best known for his many appearances as Tevye in the musical Fiddler\n        on the Roof.\n        `\n    }\n};",
      "section_id": "create-the-data"
    },
    {
      "id": "create-the-data-ex6",
      "language": "php",
      "code": "$peopleData = [\n    'Marie Curie' => [\n        'born' => 1867,\n        'died' => 1934,\n        'description' => 'Polish-French chemist and physicist. The only person ever to win two Nobel prizes for two different sciences.',\n    ],\n    'Linus Pauling' => [\n        'born' => 1901,\n        'died' => 1994,\n        'description' => 'American chemist and peace activist. One of only two people to win two Nobel prizes in different fields (chemistry and peace).',\n    ],\n    'Freddie Mercury' => [\n        'born' => 1946,\n        'died' => 1991,\n        'description' => 'British musician, best known as the lead singer of the rock band Queen.',\n    ],\n    'Marie Fredriksson' => [\n        'born' => 1958,\n        'died' => 2019,\n        'description' => 'Swedish multi-instrumentalist, mainly known as the lead singer and keyboardist of the band Roxette.',\n    ],\n    'Paul Erdos' => [\n        'born' => 1913,\n        'died' => 1996,\n        'description' => 'Hungarian mathematician, known for his eccentric personality almost as much as his contributions to many different fields of mathematics.',\n    ],\n    'Maryam Mirzakhani' => [\n        'born' => 1977,\n        'died' => 2017,\n        'description' => 'Iranian mathematician. The first woman ever to win the Fields medal for her contributions to mathematics.',\n    ],\n    'Masako Natsume' => [\n        'born' => 1957,\n        'died' => 1985,\n        'description' => 'Japanese actress. She was very famous in Japan but was primarily known elsewhere in the world for her portrayal of Tripitaka in the TV series Monkey.',\n    ],\n    'Chaim Topol' => [\n        'born' => 1935,\n        'died' => 2023,\n        'description' => \"Israeli actor and singer, usually credited simply as 'Topol'. He was best known for his many appearances as Tevye in the musical Fiddler on the Roof.\",\n    ],\n];",
      "section_id": "create-the-data"
    },
    {
      "id": "create-the-data-ex7",
      "language": "python",
      "code": "peopleData = {\n    \"Marie Curie\": {\n        \"born\": 1867, \"died\": 1934,\n        \"description\": \"\"\"\n        Polish-French chemist and physicist. The only person ever to win\n        two Nobel prizes for two different sciences.\n        \"\"\"\n    },\n    \"Linus Pauling\": {\n        \"born\": 1901, \"died\": 1994,\n        \"description\": \"\"\"\n        American chemist and peace activist. One of only two people to win two\n        Nobel prizes in different fields (chemistry and peace).\n        \"\"\"\n    },\n    \"Freddie Mercury\": {\n        \"born\": 1946, \"died\": 1991,\n        \"description\": \"\"\"\n        British musician, best known as the lead singer of the rock band\n        Queen.\n        \"\"\"\n    },\n    \"Marie Fredriksson\": {\n        \"born\": 1958, \"died\": 2019,\n        \"description\": \"\"\"\n        Swedish multi-instrumentalist, mainly known as the lead singer and\n        keyboardist of the band Roxette.\n        \"\"\"\n    },\n    \"Paul Erdos\": {\n        \"born\": 1913, \"died\": 1996,\n        \"description\": \"\"\"\n        Hungarian mathematician, known for his eccentric personality almost\n        as much as his contributions to many different fields of mathematics.\n        \"\"\"\n    },\n    \"Maryam Mirzakhani\": {\n        \"born\": 1977, \"died\": 2017,\n        \"description\": \"\"\"\n        Iranian mathematician. The first woman ever to win the Fields medal\n        for her contributions to mathematics.\n        \"\"\"\n    },\n    \"Masako Natsume\": {\n        \"born\": 1957, \"died\": 1985,\n        \"description\": \"\"\"\n        Japanese actress. She was very famous in Japan but was primarily\n        known elsewhere in the world for her portrayal of Tripitaka in the\n        TV series Monkey.\n        \"\"\"\n    },\n    \"Chaim Topol\": {\n        \"born\": 1935, \"died\": 2023,\n        \"description\": \"\"\"\n        Israeli actor and singer, usually credited simply as 'Topol'. He was\n        best known for his many appearances as Tevye in the musical Fiddler\n        on the Roof.\n        \"\"\"\n    }\n}",
      "section_id": "create-the-data"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex0",
      "language": "csharp",
      "code": "ConnectionMultiplexer muxer = ConnectionMultiplexer.Connect(\"localhost:6379\");\nIDatabase db = muxer.GetDatabase();\n\nPredictionEngine<TextData, TransformedTextData> model = GetPredictionEngine();\n\nforeach (KeyValuePair<string, dynamic> person in peopleData)\n{\n    string name = person.Key;\n    dynamic details = person.Value;\n    float[] embedding = GetEmbedding(model, details.description);\n\n    VectorSetAddRequest addRequest = VectorSetAddRequest.Member(name, embedding, null);\n    db.VectorSetAdd(\"famousPeople\", addRequest);\n\n    // Set attributes separately\n    string attributesJson = $\"{{\\\"born\\\": {details.born}, \\\"died\\\": {details.died}}}\";\n    db.VectorSetSetAttributesJson(\"famousPeople\", name, attributesJson);\n}",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex1",
      "language": "go",
      "code": "for name, details := range peopleData {\n\t\t// Generate embeddings using Hugot\n\t\tresult, err := embeddingPipeline.RunPipeline([]string{details.Description})\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Convert embedding to float64 slice\n\t\tembFloat32 := result.Embeddings[0]\n\t\tembFloat64 := make([]float64, len(embFloat32))\n\t\tfor i, v := range embFloat32 {\n\t\t\tembFloat64[i] = float64(v)\n\t\t}\n\n\t\t// Add vector to vector set\n\t\t_, err = rdb.VAdd(ctx, \"famousPeople\", name, &redis.VectorValues{Val: embFloat64}).Result()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Set attributes for the element\n\t\t_, err = rdb.VSetAttr(ctx, \"famousPeople\", name, map[string]interface{}{\n\t\t\t\"born\": details.Born,\n\t\t\t\"died\": details.Died,\n\t\t}).Result()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex2",
      "language": "java",
      "code": "RedisClient redisClient = RedisClient.create(\"redis://localhost:6379\");\n\n        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {\n            RedisAsyncCommands<String, String> asyncCommands = connection.async();\n\n            CompletableFuture<?>[] vaddFutures = new CompletableFuture[people.size()];\n\n            for (int i = 0; i < people.size(); i++) {\n                Person person = people.get(i);\n                Double[] embedding = null;\n\n                try {\n                    embedding = convertFloatsToDoubles(predictor.predict(person.description));\n                } catch (Exception e) {\n                    // ...\n                }\n\n                VAddArgs personArgs = VAddArgs.Builder.attributes(String.format(\"{\\\"born\\\": %d, \\\"died\\\": %d}\", person.born, person.died));\n                \n                vaddFutures[i] = asyncCommands.vadd(\"famousPeople\", person.name, personArgs, embedding)\n                        .thenApply(result -> {\n                            System.out.println(result); // >>> true\n                            return result;\n                        }).toCompletableFuture();\n            }\n            \n            CompletableFuture.allOf(vaddFutures).join();",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex3",
      "language": "java",
      "code": "RedisClient redisClient = RedisClient.create(\"redis://localhost:6379\");\n\n        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {\n            RedisReactiveCommands<String, String> reactiveCommands = connection.reactive();\n\n            Mono<?>[] vaddFutures = new Mono[people.size()];\n\n            for (int i = 0; i < people.size(); i++) {\n                Person person = people.get(i);\n                Double[] embedding = null;\n\n                try {\n                    embedding = convertFloatsToDoubles(predictor.predict(person.description));\n                } catch (Exception e) {\n                    // ...\n                }\n\n                VAddArgs personArgs = VAddArgs.Builder.attributes(String.format(\"{\\\"born\\\": %d, \\\"died\\\": %d}\", person.born, person.died));\n\n                vaddFutures[i] = reactiveCommands.vadd(\"famousPeople\", person.name, personArgs, embedding)\n                        .doOnNext(result -> {\n                            System.out.println(result); // >>> true\n                        });\n            }\n\n            Mono.when(vaddFutures).block();",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex4",
      "language": "java",
      "code": "RedisClient jedis = new RedisClient(\"redis://localhost:6379\");\n\n        for (Person person : people) {\n            float[] embedding;\n            try {\n                embedding = predictor.predict(person.description);\n            } catch (Exception e) {\n                // This just allows the code to compile without errors.\n                // In a real-world scenario, you would handle the exception properly.\n                embedding = new float[384];\n            }\n\n            // Add element with attributes using VAddParams\n            String attrs = String.format(\"{\\\"born\\\": %d, \\\"died\\\": %d}\", person.born, person.died);\n            boolean added = jedis.vadd(\"famousPeople\", embedding, person.name, new VAddParams().setAttr(attrs));\n            System.out.println(added); // >>> true\n        }",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex5",
      "language": "javascript",
      "code": "const client = createClient({ url: 'redis://localhost:6379' });\n\nclient.on('error', err => console.log('Redis Client Error', err));\nawait client.connect();\n\nfor (const [name, details] of Object.entries(peopleData)) {\n    const embedding = await pipe(details.description, pipeOptions);\n    const embeddingArray = Array.from(embedding.data);\n\n    await client.vAdd('famousPeople', embeddingArray, name);\n    await client.vSetAttr('famousPeople', name, JSON.stringify({\n        born: details.born,\n        died: details.died\n    }));\n}",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex6",
      "language": "php",
      "code": "$r->del('famousPeople');\n\nforeach ($peopleData as $name => $details) {\n    $embedding = $extractor($details['description'], normalize: true, pooling: 'mean');\n\n    $r->vadd('famousPeople', $embedding[0], $name);\n    $r->vsetattr('famousPeople', $name, [\n        'born' => $details['born'],\n        'died' => $details['died'],\n    ]);\n}",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "add-the-data-to-a-vector-set-ex7",
      "language": "python",
      "code": "r = redis.Redis(decode_responses=True)\n\nfor name, details in peopleData.items():\n    emb = model.encode(details[\"description\"]).astype(np.float32).tobytes()\n\n    r.vset().vadd(\n        \"famousPeople\",\n        emb,\n        name,\n        attributes={\n            \"born\": details[\"born\"],\n            \"died\": details[\"died\"]\n        }\n    )",
      "section_id": "add-the-data-to-a-vector-set"
    },
    {
      "id": "query-the-vector-set-ex0",
      "language": "csharp",
      "code": "string queryValue = \"actors\";\n\nfloat[] queryEmbedding = GetEmbedding(model, queryValue);\n\nVectorSetSimilaritySearchRequest basicQuery = VectorSetSimilaritySearchRequest.ByVector(queryEmbedding);\nusing (Lease<VectorSetSimilaritySearchResult>? actorsResults = db.VectorSetSimilaritySearch(\"famousPeople\", basicQuery))\n{\n    IEnumerable<string> resultIds = actorsResults!.Span.ToArray()\n        .Select(r => (string?)r.Member)\n        .Where(id => id != null)\n        .Select(id => $\"'{id!}'\");\n    Console.WriteLine($\"'actors': [{string.Join(\", \", resultIds)}]\");\n}",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex1",
      "language": "go",
      "code": "queryValue := \"actors\"\n\n\tqueryResult, err := embeddingPipeline.RunPipeline([]string{queryValue})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Convert embedding to float64 slice\n\tqueryFloat32 := queryResult.Embeddings[0]\n\tqueryFloat64 := make([]float64, len(queryFloat32))\n\tfor i, v := range queryFloat32 {\n\t\tqueryFloat64[i] = float64(v)\n\t}\n\n\tactorsResults, err := rdb.VSim(ctx, \"famousPeople\", &redis.VectorValues{Val: queryFloat64}).Result()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"'actors': %v\\n\", strings.Join(actorsResults, \", \"))\n\t// >>> 'actors': Masako Natsume, Chaim Topol, Linus Pauling,\n\t// Marie Fredriksson, Maryam Mirzakhani, Marie Curie, Freddie Mercury,\n\t// Paul Erdos",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex2",
      "language": "java",
      "code": "Double[] actorsEmbedding = null;\n            \n            try {\n                actorsEmbedding = convertFloatsToDoubles(predictor.predict(\"actors\"));\n            } catch (Exception e) {\n                // ...\n            }\n\n            CompletableFuture<List<String>> basicQuery = asyncCommands.vsim(\"famousPeople\", actorsEmbedding)\n                    .thenApply(result -> {\n                        System.out.println(result);\n                        // >>> [Masako Natsume, Chaim Topol, Linus Pauling, Marie Fredriksson, Maryam Mirzakhani, Marie Curie, Freddie Mercury, Paul Erdos]\n                        return result;\n                    }).toCompletableFuture();",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex3",
      "language": "java",
      "code": "Double[] actorsEmbedding = null;\n\n            try {\n                actorsEmbedding = convertFloatsToDoubles(predictor.predict(\"actors\"));\n            } catch (Exception e) {\n                // ...\n            }\n\n            Mono<java.util.List<String>> basicQuery = reactiveCommands.vsim(\"famousPeople\", actorsEmbedding)\n                    .collectList().doOnNext(result -> {\n                        System.out.println(result);\n                        // >>> [Masako Natsume, Chaim Topol, Linus Pauling, Marie Fredriksson, Maryam Mirzakhani, Marie Curie, Freddie Mercury, Paul Erdos]\n                    });",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex4",
      "language": "java",
      "code": "float[] actorsEmbedding;\n        try {\n            actorsEmbedding = predictor.predict(\"actors\");\n        } catch (Exception e) {\n            actorsEmbedding = new float[384];\n        }\n\n        List<String> basicResults = jedis.vsim(\"famousPeople\", actorsEmbedding);\n        System.out.println(basicResults);\n        // >>> [Masako Natsume, Chaim Topol, Linus Pauling, Marie Fredriksson,\n        // >>> Maryam Mirzakhani, Marie Curie, Freddie Mercury, Paul Erdos]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex5",
      "language": "javascript",
      "code": "const queryValue = \"actors\";\n\nconst queryEmbedding = await pipe(queryValue, pipeOptions);\nconst queryArray = Array.from(queryEmbedding.data);\n\nconst actorsResults = await client.vSim('famousPeople', queryArray);\n\nconsole.log(`'actors': ${JSON.stringify(actorsResults)}`);\n// >>> 'actors': [\"Masako Natsume\",\"Chaim Topol\",\"Linus Pauling\",\n// \"Marie Fredriksson\",\"Maryam Mirzakhani\",\"Freddie Mercury\",\n// \"Marie Curie\",\"Paul Erdos\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex6",
      "language": "php",
      "code": "$actorsEmbedding = $extractor('actors', normalize: true, pooling: 'mean');\n$actorsResults = $r->vsim('famousPeople', $actorsEmbedding[0]);\n\necho \"'actors': \" . json_encode($actorsResults), PHP_EOL;\n// >>> 'actors': [\"Masako Natsume\",\"Chaim Topol\",\"Linus Pauling\",\"Marie Fredriksson\",\"Maryam Mirzakhani\",\"Freddie Mercury\",\"Marie Curie\",\"Paul Erdos\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex7",
      "language": "python",
      "code": "query_value = \"actors\"\n\nactors_results = r.vset().vsim(\n    \"famousPeople\",\n    model.encode(query_value).astype(np.float32).tobytes(),\n)\n\nprint(f\"'actors': {actors_results}\")",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex8",
      "language": "plaintext",
      "code": "'actors': [\"Masako Natsume\",\"Chaim Topol\",\"Linus Pauling\",\n\"Marie Fredriksson\",\"Maryam Mirzakhani\",\"Freddie Mercury\",\n\"Marie Curie\",\"Paul Erdos\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex9",
      "language": "csharp",
      "code": "queryValue = \"actors\";\n\nqueryEmbedding = GetEmbedding(model, queryValue);\n\nVectorSetSimilaritySearchRequest limitedQuery = VectorSetSimilaritySearchRequest.ByVector(queryEmbedding);\nlimitedQuery.Count = 2;\nusing (Lease<VectorSetSimilaritySearchResult>? twoActorsResults = db.VectorSetSimilaritySearch(\"famousPeople\", limitedQuery))\n{\n    IEnumerable<string> resultIds = twoActorsResults!.Span.ToArray()\n        .Select(r => (string?)r.Member)\n        .Where(id => id != null)\n        .Select(id => $\"'{id!}'\");\n    Console.WriteLine($\"'actors (2)': [{string.Join(\", \", resultIds)}]\");\n    // >>> 'actors (2)': ['Masako Natsume', 'Chaim Topol']\n}",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex10",
      "language": "go",
      "code": "queryValue = \"actors\"\n\n\tqueryResult, err = embeddingPipeline.RunPipeline([]string{queryValue})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Convert embedding to float64 slice\n\tqueryFloat32 = queryResult.Embeddings[0]\n\tqueryFloat64 = make([]float64, len(queryFloat32))\n\tfor i, v := range queryFloat32 {\n\t\tqueryFloat64[i] = float64(v)\n\t}\n\n\ttwoActorsResults, err := rdb.VSimWithArgs(ctx, \"famousPeople\",\n\t\t&redis.VectorValues{Val: queryFloat64},\n\t\t&redis.VSimArgs{Count: 2}).Result()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"'actors (2)': %v\\n\", strings.Join(twoActorsResults, \", \"))\n\t// >>> 'actors (2)': Masako Natsume, Chaim Topol",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex11",
      "language": "java",
      "code": "VSimArgs limitArgs = VSimArgs.Builder.count(2L);\n            \n            CompletableFuture<List<String>> limitedQuery = asyncCommands.vsim(\"famousPeople\", limitArgs, actorsEmbedding)\n                    .thenApply(result -> {\n                        System.out.println(result);\n                        // >>> [Masako Natsume, Chaim Topol]\n                        return result;\n                    }).toCompletableFuture();",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex12",
      "language": "java",
      "code": "VSimArgs limitArgs = VSimArgs.Builder.count(2L);\n\n            Mono<java.util.List<String>> limitedQuery = reactiveCommands.vsim(\"famousPeople\", limitArgs, actorsEmbedding)\n                    .collectList().doOnNext(result -> {\n                        System.out.println(result);\n                        // >>> [Masako Natsume, Chaim Topol]\n                    });",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex13",
      "language": "java",
      "code": "VSimParams limitParams = new VSimParams().count(2);\n        List<String> limitedResults = jedis.vsim(\"famousPeople\", actorsEmbedding, limitParams);\n        System.out.println(limitedResults);\n        // >>> [Masako Natsume, Chaim Topol]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex14",
      "language": "javascript",
      "code": "const queryValue2 = \"actors\";\n\nconst queryEmbedding2 = await pipe(queryValue2, pipeOptions);\nconst queryArray2 = Array.from(queryEmbedding2.data);\n\nconst twoActorsResults = await client.vSim('famousPeople', queryArray2, {\n    COUNT: 2\n});\n\nconsole.log(`'actors (2)': ${JSON.stringify(twoActorsResults)}`);\n// >>> 'actors (2)': [\"Masako Natsume\",\"Chaim Topol\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex15",
      "language": "php",
      "code": "$twoActorsResults = $r->vsim('famousPeople', $actorsEmbedding[0], false, false, 2);\n\necho \"'actors (2)': \" . json_encode($twoActorsResults), PHP_EOL;\n// >>> 'actors (2)': [\"Masako Natsume\",\"Chaim Topol\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex16",
      "language": "python",
      "code": "query_value = \"actors\"\n\ntwo_actors_results = r.vset().vsim(\n    \"famousPeople\",\n    model.encode(query_value).astype(np.float32).tobytes(),\n    count=2\n)\n\nprint(f\"'actors (2)': {two_actors_results}\")\n# >>> 'actors (2)': ['Masako Natsume', 'Chaim Topol']",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex17",
      "language": "csharp",
      "code": "queryValue = \"entertainer\";\n\nqueryEmbedding = GetEmbedding(model, queryValue);\n\nVectorSetSimilaritySearchRequest entertainerQuery = VectorSetSimilaritySearchRequest.ByVector(queryEmbedding);\nusing (Lease<VectorSetSimilaritySearchResult>? entertainerResults = db.VectorSetSimilaritySearch(\"famousPeople\", entertainerQuery))\n{\n    IEnumerable<string> resultIds = entertainerResults!.Span.ToArray()\n        .Select(r => (string?)r.Member)\n        .Where(id => id != null)\n        .Select(id => $\"'{id!}'\");\n    Console.WriteLine($\"'entertainer': [{string.Join(\", \", resultIds)}]\");\n    // >>> 'entertainer': ['Chaim Topol', 'Freddie Mercury',\n    // 'Marie Fredriksson', 'Masako Natsume', 'Linus Pauling',\n    // 'Paul Erdos', 'Maryam Mirzakhani', 'Marie Curie']\n}",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex18",
      "language": "go",
      "code": "queryValue = \"entertainer\"\n\n\tqueryResult, err = embeddingPipeline.RunPipeline([]string{queryValue})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Convert embedding to float64 slice\n\tqueryFloat32 = queryResult.Embeddings[0]\n\tqueryFloat64 = make([]float64, len(queryFloat32))\n\tfor i, v := range queryFloat32 {\n\t\tqueryFloat64[i] = float64(v)\n\t}\n\n\tentertainerResults, err := rdb.VSim(ctx, \"famousPeople\", &redis.VectorValues{Val: queryFloat64}).Result()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"'entertainer': %v\\n\", strings.Join(entertainerResults, \", \"))\n\t// >>> 'entertainer': Chaim Topol, Freddie Mercury, Marie Fredriksson,\n\t// Linus Pauling, Masako Natsume, Paul Erdos,\n\t// Maryam Mirzakhani, Marie Curie",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex19",
      "language": "java",
      "code": "Double[] entertainerEmbedding = null;\n\n            try {\n                entertainerEmbedding = convertFloatsToDoubles(predictor.predict(\"entertainers\"));\n            } catch (Exception e) {\n                // ...\n            }\n\n            CompletableFuture<List<String>> entertainerQuery = asyncCommands.vsim(\"famousPeople\", entertainerEmbedding)\n                    .thenApply(result -> {\n                        System.out.println(result);\n                        // >>> [Freddie Mercury, Chaim Topol, Linus Pauling, Marie Fredriksson, Masako Natsume, Paul Erdos, Maryam Mirzakhani, Marie Curie]\n                        return result;\n                    }).toCompletableFuture();",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex20",
      "language": "java",
      "code": "Double[] entertainerEmbedding = null;\n\n            try {\n                entertainerEmbedding = convertFloatsToDoubles(predictor.predict(\"entertainers\"));\n            } catch (Exception e) {\n                // ...\n            }\n\n            Mono<java.util.List<String>> entertainerQuery = reactiveCommands.vsim(\"famousPeople\", entertainerEmbedding)\n                    .collectList().doOnNext(result -> {\n                        System.out.println(result);\n                        // >>> [Freddie Mercury, Chaim Topol, Linus Pauling, Marie Fredriksson, Masako Natsume, Paul Erdos, Maryam Mirzakhani, Marie Curie]\n                    });",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex21",
      "language": "java",
      "code": "float[] entertainerEmbedding;\n        try {\n            entertainerEmbedding = predictor.predict(\"entertainers\");\n        } catch (Exception e) {\n            entertainerEmbedding = new float[384];\n        }\n\n        List<String> entertainerResults = jedis.vsim(\"famousPeople\", entertainerEmbedding);\n        System.out.println(entertainerResults);\n        // >>> [Freddie Mercury, Chaim Topol, Linus Pauling, Marie Fredriksson,\n        // >>> Masako Natsume, Paul Erdos, Maryam Mirzakhani, Marie Curie]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex22",
      "language": "javascript",
      "code": "const queryValue3 = \"entertainer\";\n\nconst queryEmbedding3 = await pipe(queryValue3, pipeOptions);\nconst queryArray3 = Array.from(queryEmbedding3.data);\n\nconst entertainerResults = await client.vSim('famousPeople', queryArray3);\n\nconsole.log(`'entertainer': ${JSON.stringify(entertainerResults)}`);\n// >>> 'actors': [\"Masako Natsume\",\"Chaim Topol\",\"Linus Pauling\",\n// \"Marie Fredriksson\",\"Maryam Mirzakhani\",\"Freddie Mercury\",\n// \"Marie Curie\",\"Paul Erdos\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex23",
      "language": "php",
      "code": "$entertainerEmbedding = $extractor('entertainer', normalize: true, pooling: 'mean');\n$entertainerResults = $r->vsim('famousPeople', $entertainerEmbedding[0]);\n\necho \"'entertainer': \" . json_encode($entertainerResults), PHP_EOL;\n// >>> 'entertainer': [\"Chaim Topol\",\"Freddie Mercury\",\"Linus Pauling\",\"Marie Fredriksson\",\"Masako Natsume\",\"Paul Erdos\",\"Maryam Mirzakhani\",\"Marie Curie\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex24",
      "language": "python",
      "code": "query_value = \"entertainer\"\n\nentertainer_results = r.vset().vsim(\n    \"famousPeople\",\n    model.encode(query_value).astype(np.float32).tobytes()\n)\n\nprint(f\"'entertainer': {entertainer_results}\")\n# >>> 'entertainer': ['Chaim Topol', 'Freddie Mercury',\n# 'Marie Fredriksson', 'Masako Natsume', 'Linus Pauling',\n# 'Paul Erdos', 'Maryam Mirzakhani', 'Marie Curie']",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex25",
      "language": "text",
      "code": "'science': [\"Linus Pauling\",\"Marie Curie\",\"Maryam Mirzakhani\",\n\"Paul Erdos\",\"Marie Fredriksson\",\"Masako Natsume\",\n\"Freddie Mercury\",\"Chaim Topol\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex26",
      "language": "csharp",
      "code": "queryValue = \"science\";\n\nqueryEmbedding = GetEmbedding(model, queryValue);\n\nVectorSetSimilaritySearchRequest filteredQuery = VectorSetSimilaritySearchRequest.ByVector(queryEmbedding);\nfilteredQuery.FilterExpression = \".died < 2000\";\nusing (Lease<VectorSetSimilaritySearchResult>? science2000Results = db.VectorSetSimilaritySearch(\"famousPeople\", filteredQuery))\n{\n    IEnumerable<string> resultIds = science2000Results!.Span.ToArray()\n        .Select(r => (string?)r.Member)\n        .Where(id => id != null)\n        .Select(id => $\"'{id!}'\");\n    Console.WriteLine($\"'science2000': [{string.Join(\", \", resultIds)}]\");\n    // >>> 'science2000': ['Marie Curie', 'Linus Pauling',\n    // 'Paul Erdos', 'Freddie Mercury', 'Masako Natsume']\n}",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex27",
      "language": "go",
      "code": "queryValue = \"science\"\n\n\tqueryResult, err = embeddingPipeline.RunPipeline([]string{queryValue})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Convert embedding to float64 slice\n\tqueryFloat32 = queryResult.Embeddings[0]\n\tqueryFloat64 = make([]float64, len(queryFloat32))\n\tfor i, v := range queryFloat32 {\n\t\tqueryFloat64[i] = float64(v)\n\t}\n\n\tscience2000Results, err := rdb.VSimWithArgs(ctx, \"famousPeople\",\n\t\t&redis.VectorValues{Val: queryFloat64},\n\t\t&redis.VSimArgs{Filter: \".died < 2000\"}).Result()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"'science2000': %v\\n\", strings.Join(science2000Results, \", \"))\n\t// >>> 'science2000': Marie Curie, Linus Pauling, Paul Erdos, Freddie Mercury,\n\t// Masako Natsume",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex28",
      "language": "java",
      "code": "Double[] science2000Embedding = null;\n\n            try {\n                science2000Embedding = convertFloatsToDoubles(predictor.predict(\"science\"));\n            } catch (Exception e) {\n                // ...\n            }\n\n            VSimArgs filterArgs = VSimArgs.Builder.filter(\".died < 2000\");\n\n            CompletableFuture<List<String>> filteredQuery = asyncCommands.vsim(\"famousPeople\", filterArgs, science2000Embedding)\n                    .thenApply(result -> {\n                        System.out.println(result);\n                        // >>> [Marie Curie, Linus Pauling, Paul Erdos, Freddie Mercury, Masako Natsume]\n                        return result;\n                    }).toCompletableFuture();",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex29",
      "language": "java",
      "code": "Double[] science2000Embedding = null;\n\n            try {\n                science2000Embedding = convertFloatsToDoubles(predictor.predict(\"science\"));\n            } catch (Exception e) {\n                // ...\n            }\n\n            VSimArgs filterArgs = VSimArgs.Builder.filter(\".died < 2000\");\n\n            Mono<java.util.List<String>> filteredQuery = reactiveCommands.vsim(\"famousPeople\", filterArgs, science2000Embedding)\n                    .collectList().doOnNext(result -> {\n                        System.out.println(result);\n                        // >>> [Marie Curie, Linus Pauling, Paul Erdos, Freddie Mercury, Masako Natsume]\n                    });",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex30",
      "language": "java",
      "code": "float[] science2000Embedding;\n        try {\n            science2000Embedding = predictor.predict(\"science\");\n        } catch (Exception e) {\n            science2000Embedding = new float[384];\n        }\n\n        VSimParams filterParams = new VSimParams().filter(\".died < 2000\");\n        List<String> filteredResults = jedis.vsim(\"famousPeople\", science2000Embedding, filterParams);\n        System.out.println(filteredResults);\n        // >>> [Marie Curie, Linus Pauling, Paul Erdos, Freddie Mercury, Masako Natsume]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex31",
      "language": "javascript",
      "code": "const queryValue5 = \"science\";\n\nconst queryEmbedding5 = await pipe(queryValue5, pipeOptions);\nconst queryArray5 = Array.from(queryEmbedding5.data);\n\nconst science2000Results = await client.vSim('famousPeople', queryArray5, {\n    FILTER: '.died < 2000'\n});\n\nconsole.log(`'science2000': ${JSON.stringify(science2000Results)}`);\n// >>> 'science2000': [\"Linus Pauling\",\"Marie Curie\",\"Paul Erdos\",\n// \"Masako Natsume\",\"Freddie Mercury\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex32",
      "language": "php",
      "code": "$science2000Results = $r->vsim('famousPeople', $scienceEmbedding[0], false, false, null, null, null, '.died < 2000');\n\necho \"'science2000': \" . json_encode($science2000Results), PHP_EOL;\n// >>> 'science2000': [\"Linus Pauling\",\"Marie Curie\",\"Paul Erdos\",\"Masako Natsume\",\"Freddie Mercury\"]",
      "section_id": "query-the-vector-set"
    },
    {
      "id": "query-the-vector-set-ex33",
      "language": "python",
      "code": "query_value = \"science\"\n\nscience2000_results = r.vset().vsim(\n    \"famousPeople\",\n    model.encode(query_value).astype(np.float32).tobytes(),\n    filter=\".died < 2000\"\n)\n\nprint(f\"'science2000': {science2000_results}\")\n# >>> 'science2000': ['Marie Curie', 'Linus Pauling',\n# 'Paul Erdos', 'Freddie Mercury', 'Masako Natsume']",
      "section_id": "query-the-vector-set"
    }
  ]
}
