• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Client Side API Programming
  • SQL Query
  • Define Indexes Programmatically
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Clear Cache
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

Define SQL Index Programmatically

NCache allows querying the cache based on SQL queries like a database. However, unlike a database, any searchable object and its fields in NCache need to be indexed first. In this regard, NCache enables developers to define SQL indexes programmatically with ease. It lets you index all public, private, and protected primitive fields and properties. See NCache supported data types for further details.

Tip

Alternatively, you can configure SQL indexes through the NCache Management Center or PowerShell.

Note

A reference type field cannot be indexed.

Prerequisites to Define SQL Indexes Programmatically

  • .NET
  • Java
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • Searchable objects and their attributes must be indexed by either configuring indexes or defining indexes programmatically.
  • For API details, refer to: QueryIndexedAttribute, NonQueryIndexedAttribute, QueryIndexable.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • Searchable objects and their attributes must be indexed by either configuring indexes or defining indexes programmatically.
  • For API details, refer to: QueryIndexable, NonQueryIndexed, QueryIndexed.

NCache provides the flexibility to create indexes through different approaches. You can create indexes for selective fields or the whole class based on your needs. Meanwhile, certain fields can be excluded from indexing when the class is indexed. In addition, indexing support is provided for multilingual clients as well. Specifically, NCache has the following custom fields for defining indexes programmatically:

  1. QueryIndexed: Used for indexing selective fields.

  2. QueryIndexed["indexName"]: Used for indexing a field against a user-provided index name.

  3. QueryIndexable: Used for indexing the whole class.

  4. NonQueryIndexed: Used for excluding fields from indexing when a class is indexed.

Important

It is recommended to avoid indexing unnecessary fields since indexing has memory and performance overhead.

Here we discuss different approaches to create indexes in NCache using these fields.

Selective Indexing

You can create an index for a particular property or field of a class using the QueryIndexed attribute. It is defined at the primitive property or field level to indicate that the marked property or field can be indexed. The annotated properties or fields are automatically indexed.

Note

Always use QueryIndexed when you need to index only a few properties or fields of a class since it saves performance and memory costs.

This approach can be used to create indexes when relatively few properties or fields of your class require indexing. It provides the flexibility to index selective fields, where you can handpick the desired properties or fields only.

Warning

If you explicitly mark a reference field as QueryIndexed, it throws an exception "Index is not supported for <Ref Type Name>". Indexes are only supported on value types.

The following example shows how to index selective fields using QueryIndexed without indexing the whole class. NCache will automatically create indexes for the fields ID and Name only.

  • .NET
  • Java
public class Product
{
    [QueryIndexed]
    public int ID { get; set} // explicitly indexed

    [QueryIndexed]
    public string Name { get; set} // explicitly indexed

    public Decimal UnitPrice { get; set } // will not be indexed

    public Customer Customer { get; set; } // will not be indexed
}
public class Product
{
    @QueryIndexed
    public int id; // explicitly indexed

    @QueryIndexed
    public String name; // explicitly indexed

    public double unitPrice; // will not be indexed

    public Customer customer; // will not be indexed
}
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

In the example above, the index name is the same as the field name since this is the default behavior while using the QueryIndexed attribute for selective indexing. However, NCache allows you to define custom names for your fields or properties to be indexed through the QueryIndexed ("indexName") annotation. In that case, the user-specified name in the constructor will be used, while creating an index.

This can be useful when you are developing an application code across different languages, and the field names may vary. For instance, an e-commerce application has .NET and Java clients, where the .NET client names a field of the Product class as UnitPrice, while a Java client names the same field as PricePerUnit. For indexing this field, a custom name can be specified in both .NET and Java using the QueryIndexed("price") attribute. The marked field will be indexed with the name price for all clients. Now, different clients can perform the query using price in the WHERE clause or as a projection.

Warning

If a field is indexed using QueryIndexed["indexName"], querying data based on field name will throw an exception "Index not defined for field name".

The following example demonstrates how to index selective fields of a class using the index name of your choice.

  • .NET
  • Java
public class Product
{
    [QueryIndexed]
    public int ID { get; set} // explicitly indexed with index name ID

    [QueryIndexed]
    public string Name { get; set} // explicitly indexed with index name

    [QueryIndexed("price")]
    public Decimal UnitPrice { get; set } // will not be indexed

    public Customer Customer { get; set; } // will not be indexed
}
public class Product
{
    @QueryIndexed
    public int id; // explicitly indexed with index name ID

    @QueryIndexed
    public String name; // explicitly indexed with index name

    @QueryIndexed("price")
    public double unitPrice; // will not be indexed

    public Customer customer; // will not be indexed
}

Class Indexing

You can index your class using the attribute QueryIndexable. It is defined at the class level to indicate that the whole class can be indexed. When you mark a class as QueryIndexable, all the public properties and fields will be automatically indexed. If your class has a private field that requires indexing, then you need to explicitly mark it using the QueryIndexed attribute for creating its index.

This approach should only be used when you want to query index either all or most of the properties or fields of a class. Otherwise, it is not encouraged, since there is a chance that it will index unnecessary properties. Eventually, this will degrade the performance of your application due to the underlying memory and performance overhead of indexing.

Warning
  • It is not recommended to use QueryIndexable, unless all or most of the properties or fields require indexing, since indexing has memory and performance costs.
  • Marking a class as QueryIndexable doesn't index private fields. In this case, you'll need to individually mark each private field as QueryIndexable to index it.

The following example demonstrates indexing the fields of a class named Product using the QueryIndexable, attribute. This will index the ID, Name, and UnitPrice fields. The field Category is explicitly marked as QueryIndexed since it is private. Indexing Customer will be ignored since it is a reference field pointing to the object of the Customer class, while NCache does not allow indexing reference fields.

  • .NET
  • Java
[QueryIndexable]
public class Product
{
    public int ID { get; set} // auto index

    public string Name { get; set} // auto index

    public Decimal UnitPrice { get; set } // auto index

    [QueryIndexed]
    private string Category { get; set } // explicitly marked for indexing

    public Customer Customer { get; set; } // will not be indexed
}
@QueryIndexable
public class Product
{
    public int id; // auto index

    public String name; // auto index

    public double unitPrice; // auto index

    @QueryIndexed
    private String category; // explicitly marked for indexing

    public Customer customer; // will not be indexed
}

Excluding Fields from Indexing

You can use the NonQueryIndexed attribute to prevent the indexing of unrequired properties or fields when your class is indexed. The attribute NonQueryIndexed is defined at the primitive property or field level to indicate that the property or field should be excluded from indexing when the class itself is marked as QueryIndexable. All the public properties and fields will be automatically indexed. The fields marked with the NonQueryIndexed attribute will be excluded from indexing. You can use a combination of QueryIndexable and NonQueryIndexed when most of the properties require indexing except a few.

The following example shows how to exclude the field UnitPrice from indexing by explicitly marking it as NonQueryIndexed when the class itself is indexed. This will ignore the indexing of the annotated field.

  • .NET
  • Java
[QueryIndexable]
public class Product
{
    public int ID { get; set} // auto index

    public string Name { get; set} // auto index

    [NonQueryIndexed]
    public Decimal UnitPrice { get; set } // will not be indexed

    public Customer Customer { get; set; } // will not be indexed
}
@QueryIndexable
public class Product
{
    public int id; // auto indexed

    public String name; // auto indexed

    @NonQueryIndexed
    public double unitPrice; // will not be indexed

    public Customer customer; // will not be indexed
}
Note

NCache allows you to suppress any errors associated with creating indexes via the NCacheServer.SuppressIndexNotDefinedException tag in the NCache Service Config files.

Additional Resources

NCache provides a sample application for SQL Queries on GitHub.

See Also

.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.

In This Article
  • Prerequisites to Define SQL Indexes Programmatically
  • Selective Indexing
  • Class Indexing
  • Excluding Fields from Indexing
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top